Protobuf C++ serialize到char*的方法

通过admin

Protobuf C++ serialize到char*的方法

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();

关于作者

admin administrator

发表评论