问题
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:
- Strings, bytes and repeated fields of any type map to callback functions by default.
- 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.- If
(nanopb).fixed_length
is set totrue
and(nanopb).max_size
is also set, then bytes map to an inline byte array of fixed size.- 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