4

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.

Autonomous
  • 8,935
  • 1
  • 38
  • 77
Robert Buhren
  • 86
  • 1
  • 1
  • 4
  • Take a look at this: https://code.google.com/p/protobuf-c/wiki/RPC_Example lots of code, but they're using strings. Looks like they just `malloc` the amount they need for the string and treat it as if it was a regular string. Bytes would work the same way. I like NanoPB more, it supports callbacks and fixed-width, simpler to use. – Misha M Dec 28 '13 at 06:18
  • @MishaM, I know I'm a bit off-topic, do you have any examples of how to extract a bytes/string field from a NanoPB message? I am struggling with grabbing the fixed-width string from the callback. – Mike Lambert Jun 28 '18 at 06:00
  • @MikeLambert you mean once you receive a message and one of the fields is a string/byte array? I'm not sure I follow here – Misha M Jun 30 '18 at 14:28

2 Answers2

6

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.

foma
  • 457
  • 1
  • 7
  • 22
2

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;
br1
  • 425
  • 4
  • 9