我写了一些被https://github.com/protobuf-c/protobuf-c/wiki/Examples引用的c代码
Operation msg = OPERATION__INIT;
uint8_t *buf;
unsigned len;
msg.operation = "d";
msg.tracking_id = 1;
msg.x = 0.22556;
msg.y = 0.65110;
len = operation__get_packed_size(&msg);
buf = malloc(len);
operation__pack(&msg, buf);
fprintf(stderr,"Writing %d serialized bytes\n", len);
Operation *msg1 = operation__unpack(NULL, len, buf);
printf("operation:%s\n", msg1->operation);
printf("%d\n", msg1->tracking_id);
printf("%f\n", msg1->x);
printf("%f\n", msg1->y);
打印结果如下:
Writing 3 serialized bytes
operation:d
0
0.000000
0.000000
为什么tracking_id
、x
和y
为零?我的代码有问题吗?
操作定义如下:
syntax = "proto2";
message Operation {
required string operation = 1;
optional int32 tracking_id = 2;
optional double x = 3;
optional double y = 4;
}
最佳答案
tracking_id
、x
和y
是可选
,因此您需要指定是否提供它们.
根据您链接的页面,您需要添加以下内容:
msg.has_tracking_id = 1;
msg.has_x = 1;
msg.has_y = 1;
同样,接收者需要检查是否提供了值。
if (msg1->has_tracking_id)
printf("%d\n", msg1->tracking_id);
if (msg1->has_x)
printf("%f\n", msg1->x);
if (msg1->has_y)
printf("%f\n", msg1->y);
不要忘记释放缓冲区。
amessage__free_unpacked(msg1, NULL);
关于c protobuf数据无法反序列化/解包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58909200/