我正在尝试协议缓冲序列化& C language中的反序列化。 我创建了一个learn.proto消息,如下所示,只是尝试将消息打包到* uint8_t并解压缩。
syntax = "proto3";
package learn;
message learnmessage {
enum LearnType {
ZERO = 0;
ONE = 1;
TWO = 2;
THREE = 3;
FOUR = 4;
FIVE = 5;
SIX = 6;
}
LearnType typ = 1;
string text = 2;
}
解包后,无论我打包到原始消息中,都会获得枚举值,始终为零。但反序列化后文本字段值仍然正常。
例如,我正在打包enum LEARN__LEARNMESSAGE__LEARN_TYPE__THREE
但在解压后,它会变为LEARN__LEARNMESSAGE__LEARN_TYPE__ZERO
我按gcc -o program mycode.c learn.pb-c.c -lprotobuf-c
有人可以帮助我弄清楚我正在做的错误:
#include <stdio.h>
#include <stdlib.h>
#include "learn.pb-c.h"
int main()
{
Learn__Learnmessage msg = LEARN__LEARNMESSAGE__INIT, *msgCopy;
size_t len;
uint8_t *msgStr;
msg.typ = LEARN__LEARNMESSAGE__LEARN_TYPE__THREE; //corresponds to enum value 3
msg.text = "again";
len = learn__learnmessage__get_packed_size(&msg); //get the length of the uint8_t needed to pack the message
msgStr = malloc(len * sizeof(uint8_t));
learn__learnmessage__pack(&msg, msgStr); //packs the message into msgStr
msgCopy = learn__learnmessage__unpack(NULL, len, msgStr); //unpack the message into msgCopy
printf("Orginal: %d \n", msg.typ); //prints 3 (expected)
printf("Copy: %d \n", msgCopy->typ); //prints 0 (un-expected)
}
答案 0 :(得分:1)
生成的C代码中有一个字段protobuf_c_boolean has_typ;
。将其设置为1后,事情开始按预期工作。
所以代码实际上必须是:
msg.typ = LEARN__LEARNMESSAGE__LEARN_TYPE__THREE;
msg.has_typ = 1;
msg.text = "again";