c protobuf数据无法反序列化/解包?

标签 c protocol-buffers

我写了一些被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_idxy可选,因此您需要指定是否提供它们.

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

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/

相关文章:

在 Ruby 中创建 C 扩展

C - 强制终止时刷新文件缓冲区

c - MPI 矩阵 vector 乘法返回有时正确有时奇怪的值

c - 跳过可选的 scanf 参数

c - 在列表中添加一个元素

dart - Windows的dart-protoc-plugin的替代品

c++ - 如何从内存缓冲区加载 tensorflow 图

javascript - 解码gtfs-r数据时"Illegal group end indicator...(not a group)"

docker - 建立grpc protobuf需要太长时间

go - 从 protobuf 更新数据