4

我正在尝试在 c 项目中使用 protobuf-c 来传输一些数据。此处缺少“字符串”和“字节”数据类型的示例

任何人都可以为那些提供一个小例子吗?我的问题是我不知道如何为具有这些数据类型的消息分配内存,因为它们的大小在编译时是未知的。

4

2 回答 2

6

请查看以下链接:

https://groups.google.com/forum/#!topic/protobuf-c/4ZbQwqLvVdw

https://code.google.com/p/protobuf-c/wiki/libprotobuf_c(虚拟缓冲区)

基本上ProtobufCBinaryData是一个结构,您可以按照第一个链接中的描述访问其文件。我还在下面展示了一个小示例(类似于官方 wiki https://github.com/protobuf-c/protobuf-c/wiki/Examples上的示例)。

你的原型文件:

message Bmessage {
  optional bytes value=1;
}

现在假设您收到了这样的消息并想要提取它:

  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);

希望有帮助。

于 2014-03-26T19:34:57.623 回答
2

这是一个如何用字节构造消息的示例:

message MacAddress {
    bytes b = 1;        // 6 bytes size
}

和C代码:

uint8_t mac[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06 };

MacAddress ma = MAC_ADDRESS__INIT;
ma.b.data = mac;
ma.b.len = 6;
于 2018-02-12T10:05:42.540 回答