时间:2021-05-30 08:44:50 | 栏目:C代码 | 点击:次
protobuf的Demo程序是
C++版本的protubuf有几种serialize和unSerialize的方法:
方法一:
官方demo程序采用的是
fstream output(argv[1], ios::out | ios::trunc | ios::binary);
if (!address_book.SerializeToOstream(&output)) {
cerr << "Failed to write address book." << endl;
return -1;
}
// Read the existing address book.
fstream input(argv[1], ios::in | ios::binary);
if (!input) {
cout << argv[1] << ": File not found. Creating a new file." << endl;
} else if (!address_book.ParseFromIstream(&input)) {
cerr << "Failed to parse address book." << endl;
return -1;
}
而如果想序列到char *,并且通过socket传输,则可以使用:
方法二:
void *buffer = malloc(size);
address_book.SerializeToArray(buffer, size);
方法三:
std::ostringstream stream;
address_book.SerializeToOstream(&stream);
string text = stream.str();
char* ctext = string.c_str();