Eamorr
Eamorr

Reputation: 10012

How to serialize to char* using Google Protocol Buffers?

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

Upvotes: 24

Views: 53038

Answers (5)

David Schwartz
David Schwartz

Reputation: 182769

You can use ByteSizeLong() to get the number of bytes the message will occupy and then SerializeToArray() to populate an array with the encoded message.

Upvotes: 6

Hemaolle
Hemaolle

Reputation: 2148

Solution with a smart pointer for the array:

size_t size = address_book.ByteSizeLong();
std::unique_ptr<char[]> serialized(new char[size]);
address_book.SerializeToArray(&serialized[0], static_cast<int>(size));

Upvotes: 5

Evgen Bodunov
Evgen Bodunov

Reputation: 5926

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.

Upvotes: 50

GhislainS
GhislainS

Reputation: 11

Still one more line of code to take care of the fact that the serialized data can contain zero's.

std::ostringstream stream;
address_book.SerializeToOstream(&stream);

string text = stream.str();
char* ctext = text.c_str();    // ptr to serialized data buffer
//  strlen(ctext) would wrongly stop at the 1st 0 it encounters.
int   data_len = text.size();  // length of serialized data

Upvotes: 1

Fox32
Fox32

Reputation: 13560

You can serailze the output to a ostringstream and use stream.str() to get the string and then access the c-string with string.c_str().

std::ostringstream stream;
address_book.SerializeToOstream(&stream);

string text = stream.str();
char* ctext = text.c_str();

Don't forget to include sstream for std::ostringstream.

Upvotes: 12

Related Questions