我的Protobuf消息由3个双打组成
syntax = "proto3";
message TestMessage{
double input = 1;
double output = 2;
double info = 3;
}
当我将这些值设置为
时test.set_input(2.3456);
test.set_output(5.4321);
test.set_info(5.0);
序列化消息看起来像
00000000 09 16 fb cb ee c9 c3 02 40 11 0a 68 22 6c 78 ba |........@..h"lx.|
00000010 15 40 19 |.@.|
00000013
使用test.serializeToArray
时,使用相同的Protobuf消息无法通过GO程序成功化。尝试从C 程序读取它时,我得到了0个信息,因此消息似乎已损坏。
使用test.serializeToOstream
时,我收到了此消息,可以通过GO和C 程序成功化。
00000000 09 16 fb cb ee c9 c3 02 40 11 0a 68 22 6c 78 ba |........@..h"lx.|
00000010 15 40 19 00 00 00 00 00 00 14 40 |.@........@|
0000001b
将值设置为
test.set_input(2.3456);
test.set_output(5.4321);
test.set_info(5.5678);
由test.serializeToArray
和test.serializeToOstream
产生的序列化消息看起来像
00000000 09 16 fb cb ee c9 c3 02 40 11 0a 68 22 6c 78 ba |........@..h"lx.|
00000010 15 40 19 da ac fa 5c 6d 45 16 40 |.@....mE.@|
0000001b
可以通过我的GO和CPP程序成功阅读。
我在这里想念什么?为什么serializeToArray
在第一种情况下不起作用?
编辑:事实证明,serializetostring也很好。
在这里我用于比较的代码:
file_a.open(FILEPATH_A);
file_b.open(FILEPATH_B);
test.set_input(2.3456);
test.set_output(5.4321);
test.set_info(5.0);
//serializeToArray
int size = test.ByteSize();
char *buffer = (char*) malloc(size);
test.SerializeToArray(buffer, size);
file_a << buffer;
//serializeToString
std::string buf;
test.SerializeToString(&buf);
file_b << buf;
file_a.close();
file_b.close();
为什么SerializetoArray无法正常工作?
edit2:
使用file_b << buf.data()
代替file_b << buf.data()
时,数据也会损坏,但是为什么?
我认为您犯的错误是将二进制视为字符数据并使用字符数据API。在第一个nil byte(0(处,许多API stop ,但这是Protobuf binary中的完全有效的值。
您需要确保基本上不使用任何此类API-纯粹坚持二进制安全API。
由于您指出size
为27,因此所有这些都适合。
基本上,5.0的二进制表示形式包括0个字节,但是您很容易看到其他值的问题。