Rob*_*ren 4 c malloc protocol-buffers
我正在尝试在 c 项目中使用 protobuf-c 来传输一些数据。此处缺少“字符串”和“字节”数据类型的示例
任何人都可以为那些提供一个小例子吗?我的问题是我不知道如何为具有这些数据类型的消息分配内存,因为它们的大小在编译时是未知的。
请查看以下链接:
https://groups.google.com/forum/#!topic/protobuf-c/4ZbQwqLvVdw
https://code.google.com/p/protobuf-c/wiki/libprotobuf_c(虚拟缓冲区)
基本上ProtobufCBinaryData是一个结构,您可以按照第一个链接中的描述访问其文件。我还在下面展示了一个小例子(类似于官方维基https://github.com/protobuf-c/protobuf-c/wiki/Examples上的例子)。
你的原型文件:
message Bmessage {
optional bytes value=1;
}
Run Code Online (Sandbox Code Playgroud)
现在假设您收到了这样的消息并想要提取它:
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);
Run Code Online (Sandbox Code Playgroud)
希望有帮助。
| 归档时间: |
|
| 查看次数: |
9039 次 |
| 最近记录: |