I'm trying to use protobuf-c in a c-project to transfer some data. The examples for the "string" and the "byte" datatype are missing here
Can anyone provide a small example for those? My problem is that I don't know how to allocate memory for a message with these datatypes since their size is not known at compile time.
Please have a look at the following links:
https://groups.google.com/forum/#!topic/protobuf-c/4ZbQwqLvVdw
https://code.google.com/p/protobuf-c/wiki/libprotobuf_c (Virtual Buffers)
Basically ProtobufCBinaryData
is a structure and you can access its fileds as described in the first link. I am also showing a small example below (similar to those on the official wiki https://github.com/protobuf-c/protobuf-c/wiki/Examples).
Your proto file:
message Bmessage {
optional bytes value=1;
}
Now imagine you have recieved such message and want to extract it:
BMessage *msg;
// Read packed message from standard-input.
uint8_t buf[MAX_MSG_SIZE];
size_t msg_len = read_buffer (MAX_MSG_SIZE, buf);
// Unpack the message using protobuf-c.
msg = bmessage__unpack(NULL, msg_len, buf);
if (msg == NULL) {
fprintf(stderr, "error unpacking incoming message\n");
exit(1);
}
// Display field's size and content
if (msg->has_value) {
printf("length of value: %d\n", msg->value.len);
printf("content of value: %s\n", msg->value.data);
}
// Free the unpacked message
bmessage__free_unpacked(msg, NULL);
Hope that helps.
Here is an example how to construct a message with bytes:
message MacAddress {
bytes b = 1; // 6 bytes size
}
And C code:
uint8_t mac[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06 };
MacAddress ma = MAC_ADDRESS__INIT;
ma.b.data = mac;
ma.b.len = 6;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With