在proto中定义了一个bytes数据,例如:
message Msg {
...
bytes data = 3
...
}
如果data使用普通的 string,一般不会有问题。
如果想在data里放二进制数据,例如:
char dataBytes[8];
dataBytes[0] = 0x11;
dataBytes[1] = 0xFF;
dataBytes[2] = 0x10;
dataBytes[3] = 0x00;
dataBytes[4] = 0x01;
dataBytes[5] = 0x00;
dataBytes[6] = 0x20;
dataBytes[7] = 0xFF;
这个时候,中间有0x00,在序列化的时候,有2点一定需要注意:
1,string一定要指定长度
std::string msgData(dataBytes, sizeof(dataBytes));
msg.set_data(msgData);
2,发送的时候,或者反序列化的时候
例如序列化后Hexadecimal String: 086518012a0473656e6430bf843d380140014a0811ff1000010020ff
长度的计算不要使用strlen,否则会导致解析出来的data里00后面的数据丢失。
serializedDataString.size(); // 长度为28
// strlen会有问题,遇到00长度会计算错误,计算出来长度为23
// strlen(serializedDataString.c_str())