我目前正在使用两种消息协议,一种是google proto,另一种是c结构。将Google协议缓冲区消息(MessageLite
)转换为字节数组的最佳解决方案是什么?
例如,我想要转换以下Google Proto消息:
message GoogleRequest
{
optional int32 request = 1 [default = 0];
}
至:
struct Request
{
int request;
};
我已经尝试了以下方法,但是它不起作用:
GoogleRequest reqMsg;
reqMsg.set_request(1234);
int size = reqMsg.ByteSize();
Request* reqStruct = new Request;
reqMsg.SerializeToArray((void*)reqStruct , size);
任何建议,或者是最好的方法:
reqStruct->request = reqMsg.request();
我有很多消息类型,并且找到一种通用的方法非常好。
您说您想将消息转换为字节数组,但是您的代码建议您尝试将其转换为C struct(Request
)。不支持转换为C结构。转换为字节数组(即的数组char
)很容易:
int size = reqMsg.ByteSize();
char* array = new char[size];
reqMsg.SerializeToArray(array, size);
或者,另一种方式:
std::string bytes = reqMsg.SerializeAsString();
const char* array = bytes.data();
int size = bytes.size();
但是,此数组不是结构,根据内容的不同,它可以具有许多不同的大小。除了编写手动在每个字段上复制的代码外,无法转换为结构。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句