using repeated field rule in a message with nanopb in c

强颜欢笑 提交于 2019-12-11 03:45:16

问题


I'm having a hard time in realizing how to use the repeated field rule. for example, this is my .proto:

message Test
{
   repeated float   value = 1;
}

now, I'm initialize a new Test object:

Test test = test_init_zero()

Finally, I want to assign some values. For example:

float values[] = { 1.0, 2.2, 5.5, 7.13 }

My question is how can I assign them? is it like

test.value = values
//or
test.value[0] = values[0] //... etc.

and then, how do I read them back?


回答1:


This depends on how you define the repeated field inside the proto file. According to nanopb docs, you either just specify the repeated field like you did, and then use a callback function to handle each item separately during encoding/decoding, or you use nanopb-specific settings so have a fixed length array:

  1. Strings, bytes and repeated fields of any type map to callback functions by default.
  2. If there is a special option (nanopb).max_size specified in the .proto file, string maps to null-terminated char array and bytes map to a structure containing a char array and a size field.
  3. If (nanopb).fixed_length is set to true and (nanopb).max_size is also set, then bytes map to an inline byte array of fixed size.
  4. If there is a special option (nanopb).max_count specified on a repeated field, it maps to an array of whatever type is being repeated. Another field will be created for the actual number of entries stored.

For example, byte arrays need to use max_size:

required bytes data = 1 [(nanopb).max_size = 40, (nanopb).fixed_length = true];

And this would create the following field, when compiled using nanopb:

// byte arrays get a special treatment in nanopb
pb_byte_t data[40];

Or, for a float, you would use max_count according to rule 4.:

repeated float data = 1 [(nanopb).max_count = 40];

And then you'll get:

size_t data_count;
float data[40];

If you simply define a repeated field like you did, then nanopb will create a callback function:

// repeated float value = 1;
pb_callback_t value;

Which means you will have to provide your own function which will handle each incoming item:

yourobject.value.arg = &custom_args;
yourobject.value.funcs.decode = custom_function_for_decoding;


来源:https://stackoverflow.com/questions/45844168/using-repeated-field-rule-in-a-message-with-nanopb-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!