Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of using "byte" datatype with protobuf-c

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.

like image 962
Robert Buhren Avatar asked Feb 15 '23 04:02

Robert Buhren


2 Answers

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.

like image 86
foma Avatar answered Feb 24 '23 01:02

foma


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;
like image 34
br1 Avatar answered Feb 24 '23 01:02

br1