Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize to char* using Google Protocol Buffers?

Tags:

I want to serialize my protocol buffer to a char*. Is this possible? I know one can serialize to file as per:

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.

How to do this? Please bear in mind that I'm very new to C++.

like image 910
Eamorr Avatar asked Feb 06 '12 10:02

Eamorr


People also ask

How is Protobuf serialized?

The Protobuf serialization mechanism is given through the protoc application, this compiler will parse the . proto file and will generate as output, source files according to the configured language by its arguments, in this case, C++. You can also obtain more information about, reading the section compiler invocation.

How does Google Protobuf work?

Protocol buffers are a combination of the definition language (created in . proto files), the code that the proto compiler generates to interface with data, language-specific runtime libraries, and the serialization format for data that is written to a file (or sent across a network connection).

Does Protobuf handle endianness?

Protocol buffers messages always use little-endian encoding. Implementations running on big-endian architectures should be doing the conversions automatically. If you are receiving data in wrong order, I would suggest using protoc --decode_raw to see whether the error occurs on the transmission or reception side.


1 Answers

That's easy:

size_t size = address_book.ByteSizeLong();  void *buffer = malloc(size); address_book.SerializeToArray(buffer, size); 

Check documentation of MessageLite class also, it's parent class of Message and it contains useful methods.

like image 196
Evgen Bodunov Avatar answered Oct 20 '22 06:10

Evgen Bodunov