gpt4 book ai didi

c - 协议(protocol)消息反序列化不当

转载 作者:行者123 更新时间:2023-11-30 14:59:11 32 4
gpt4 key购买 nike

我正在 C language 中尝试 Protocol Buffer 序列化和反序列化。我创建了一个 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;
}

解包后,无论我将什么打包到原始消息中,获得的枚举值始终为零。但反序列化后文本字段值仍然正确。例如,我正在打包枚举 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)


}

最佳答案

生成的C代码中有一个字段protobuf_c_boolean has_typ;。将其设置为 1 后,一切开始按预期工作。

所以代码实际上必须是:

msg.typ = LEARN__LEARNMESSAGE__LEARN_TYPE__THREE;
msg.has_typ = 1;
msg.text = "again";

关于c - 协议(protocol)消息反序列化不当,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42968475/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com