[英]How to exchange binary data between c++ and java using protocol buffers and ZeroMQ
Α protocol buffers beginner here. 这里是一个协议缓冲区初学者。
I have a C++ application that has access to binary data via a method call that returns char *
. 我有一个C ++应用程序,该应用程序可以通过返回char *
的方法调用来访问二进制数据。
I would like to put these pieces of data to a buffer
, 我想将这些数据放入buffer
,
serialize them using protocol buffers, 使用协议缓冲区序列化它们,
send them over the network using ZeroMQ
and receive and parse them from a Java application. 使用ZeroMQ
通过网络发送它们,并从Java应用程序接收并解析它们。
This is what I came up so far: 到目前为止,这是我提出的内容:
// Pointer to the binary data
char *buffer = buf->Buffer();
// Serialize data using protocol buffers
messaging::RequestMessage* msg = new messaging::RequestMessage;
msg->set_description("data");
msg->set_value(buffer);
int size = msg->ByteSize();
char *serialBuffer = malloc(size);
msg->SerializeToArray(serialBuffer, size);
// Send data using ZeroMQ
mq.connect(ss.str());
mq.send((char *)serialBuffer, size);
package messaging;
message RequestMessage {
required string description = 1;
optional bytes value = 2;
}
// Receive data to byte[] array
byte[] request;
// Deserialize data
Request.RequestMessage msg = Request.RequestMessage.parseFrom(request);
byte[] test = msg.getValue().toByteArray();
System.out.println("Size of bytestring value " + msg.getValue().size());
process(msg.getDescription(), msg.getValue().toByteArray());
Is this correct? 这个对吗?
Although the binary data size is 37062 bytes, 尽管二进制数据大小为37062字节,
msg->ByteSize()
only reports 4 bytes, so I guess that protocol buffers treat char*
as a string
array and stop as soon as an \\0
is found. msg->ByteSize()
仅报告4个字节,因此我想协议缓冲区msg->ByteSize()
char*
视为string
数组,并在找到\\0
立即停止。
What should I use instead? 我应该怎么用呢?
msg->set_value(buffer);
Here, you aren't giving protobuf any way to know how big buffer
is. 在这里,您没有给protobuf提供任何方法来知道有多大的buffer
。 You are only passing it a pointer to the beginning of the buffer. 您仅向其传递了指向缓冲区开头的指针。 Therefore protobuf assumes you're using the C convention of passing a string which ends at the first NUL byte. 因此,protobuf假定您正在使用C约定来传递以第一个NUL字节结尾的字符串。
In order to tell protobuf how big the buffer is, you must also pass as size: 为了告诉protobuf缓冲区有多大,还必须按大小传递:
msg->set_value(buffer, buf->Size());
(I'm only guessing that buf
has a Size()
method; you'll have to check the documentation for whatever type this is.) (我只是在猜测buf
有一个Size()
方法;您必须检查文档中的任何类型。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.