C++ 如何使用 Google Protocol Buffers 序列化为 char*?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9158576/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to serialize to char* using Google Protocol Buffers?
提问by Eamorr
I want to serialize my protocol buffer to a char*. Is this possible? I know one can serialize to file as per:
我想将我的协议缓冲区序列化为 char*。这可能吗?我知道可以按以下方式序列化到文件:
fstream output("/home/eamorr/test.bin", ios::out | ios::trunc | ios::binary);
if (!address_book.SerializeToOstream(&output)) {
cerr << "Failed to write address book." << endl;
return -1;
}
But I'd like to serialize to a C-style char* for transmission across a network.
但我想序列化为 C 风格的 char* 以通过网络传输。
How to do this? Please bear in mind that I'm very new to C++.
这该怎么做?请记住,我对 C++ 很陌生。
回答by Evgen Bodunov
That's easy:
这很容易:
size_t size = address_book.ByteSizeLong();
void *buffer = malloc(size);
address_book.SerializeToArray(buffer, size);
Check documentation of MessageLite classalso, it's parent class of Message and it contains useful methods.
检查MessageLite 类的文档,它是 Message 的父类,它包含有用的方法。
回答by Fox32
You can serailze the output to a ostringstream
and use stream.str()
to get the string and then access the c-string with string.c_str()
.
您可以将输出序列化为 aostringstream
并用于stream.str()
获取字符串,然后使用string.c_str()
.
std::ostringstream stream;
address_book.SerializeToOstream(&stream);
string text = stream.str();
char* ctext = text.c_str();
Don't forget to include sstream
for std::ostringstream
.
不要忘记包含sstream
for std::ostringstream
。
回答by David Schwartz
You can use ByteSizeLong()
to get the number of bytes the message will occupy and then SerializeToArray()
to populate an array with the encoded message.
您可以使用ByteSizeLong()
来获取消息将占用的字节数,然后SerializeToArray()
使用编码的消息填充数组。
回答by Hemaolle
Solution with a smart pointer for the array:
使用数组智能指针的解决方案:
size_t size = address_book.ByteSizeLong();
std::unique_ptr<char[]> serialized(new char[size]);
address_book.SerializeToArray(&serialized[0], static_cast<int>(size));
回答by GhislainS
Still one more line of code to take care of the fact that the serialized data can contain zero's.
还有一行代码来处理序列化数据可以包含零的事实。
std::ostringstream stream;
address_book.SerializeToOstream(&stream);
string text = stream.str();
char* ctext = text.c_str(); // ptr to serialized data buffer
// strlen(ctext) would wrongly stop at the 1st 0 it encounters.
int data_len = text.size(); // length of serialized data