简体   繁体   中英

Set elements from array pointer into protobuf in C++

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM