我在理解如何使用 nanopb 正确编码/解码 protobuf 消息中的字符串方面有点挣扎。编码/解码的消息如下所示:
struct CDAPMessage {
//...
optional string objName = 6; // Object name, unique in its class
optional int64 objInst = 7; // Unique object instance
//...
}
该消息有更多字段,但它们都是相同的类型(或者optional string
或optional int
)。
编译后,在.pb.h
文件中,我有
typedef struct _CDAPMessage {
//...
pb_callback_t objName; /* Object name, unique in its class */
bool has_objInst;
int64_t objInst; /* Unique object instance */
//...
}
我想要一个功能来解码整个消息,就像这样:
CDAPMessage *
cdap_decode_msg(void *buf, size_t msg_len)
{
// Allocate space for the decoded message
CDAPMessage msg = CDAPMessage_init_zero;
// Create a stream that reads from the buffer.
pb_istream_t stream = pb_istream_from_buffer(buf, msg_len);
/* Now we are ready to decode the message. */
bool status = pb_decode(&stream, CDAPMessage_fields, &msg);
// Check for errors...
if (!status) {
error("Decoding failed: %s\n", PB_GET_ERROR(&stream));
return NULL; // Returning empty message
}
return CDAPMessage;
}
但是,使用这种方法我对整数进行编码没有问题,但它不适用于编码字符串(它不会抱怨,只是不会编码任何东西)。我想这是因为我应该在结构中使用某种函数指针pb_callback_t
进行编码/解码,以及在args
字段中包含字符串值。
我真的找不到一个很好的例子来做我想做的事,虽然官方文档对我来说有点,但我不能真正从中清楚地了解一些东西。因此,任何指向正确方向的帮助将不胜感激。