c protobuf数据不能deserialize/unpack?

c protobuf data can‘t deserialize/unpack?

我写了一些被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_idxy 为零?我的代码有问题吗?

操作定义如下:

syntax = "proto2";

message Operation {
    required string operation = 1;
    optional int32 tracking_id = 2;
    optional double x = 3;
    optional double y = 4;
}

tracking_idxyoptional,需要注明是否提供

根据您链接的页面,您需要添加以下内容:

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