ravi
ravi

Reputation: 6338

Confused regarding the use of Message::ParseFromIstream in Protocol Buffers

I am receiving the data as unsigned char*, which contains a byte array.

unsigned char* byteptr = static_cast<unsigned char*>(msg.data());

I want to initialize my protocol buffer which is an address book. I think the best possible match is to use ParseFromIstream is following:

my_address_book.ParseFromIstream()

Regarding the byte array, which is unsigned char*. Since the length of the byte array is not known at compile time, there are two options:

Option 1. Variable length array

unsigned char bytearray[msg.size()];
std::copy(byteptr, byteptr + msg.size(), bytearray);

Option 2. Dynamically allocated array and delete it once done

unsigned char* bytearray = new unsigned char [msg.size()];
std::copy(byteptr, byteptr + msg.size(), bytearray);

I have following questions:

  1. How to use ParseFromIstream in case of unsigned char*?
  2. Considering that the better performance (fast execution speed) is the priority, which option is best among above two?

Upvotes: 0

Views: 3018

Answers (1)

Kenton Varda
Kenton Varda

Reputation: 45236

You should use ParseFromArray(), which takes a pointer and a size:

my_address_book.ParseFromArray(msg.data(), msg.size())

There is no need to copy the data to a new array at all.

Upvotes: 4

Related Questions