How to serialize to char* using Google Protocol Buffers?

Eamorr picture Eamorr · Feb 6, 2012 · Viewed 38.4k times · Source

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++.

Answer

Evgen Bodunov picture Evgen Bodunov · Feb 6, 2012

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.