protobuf的Demo程式是
C++版本的protubuf有幾種serialize和unSerialize的方法:
方法一:
官方demo程式採用的是
複製代碼 代碼如下: // Write the new address book back to disk.
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;
}
上面採用的是fstream,把資料序列(反序列)打磁碟檔案中。
而如果想序列到char *,並且通過socket傳輸,則可以使用:
方法二:
複製代碼 代碼如下:int size = address_book.ByteSize();
void *buffer = malloc(size);
address_book.SerializeToArray(buffer, size);
方法三:
複製代碼 代碼如下:使用ostringstream ,
std::ostringstream stream;
address_book.SerializeToOstream(&stream);
string text = stream.str();
char* ctext = string.c_str();