Home > Software engineering >  Set elements from array pointer into protobuf in C
Set elements from array pointer into protobuf in C

Time:08-05

I have a pointer to an array called array which is defined as uint16_t *array. I have another variable called size that shows how many elements there is. I have a field in a protobuf message defined as:

required bytes array = 1;

How can I use the generated method protoMessage.set_array to convert my array into the field?

Edit:

I realized I could do protoMessage.set_array(array, sizeof(uint16_t) * size); to put the data in, still unsure about how to properly set it out.

CodePudding user response:

Since Protobuf's bytes type is a std::string, you need to serialize your uint16_t array into a string, and calls set_array.

protoMessage.set_array(array, sizeof(uint16_t) * size);

However, your serialization might not be portable, because of the big/little endian problem.

In your case, why not define your proto message field as repeated? So that you can put your uint16_t array into the field, and protobuf will do the serialization work for you.

repeated uint32 array = 1;
protoMessage.mutable_array()->Add(array, array   size);
  • Related