gpt4 book ai didi

c++ - 如何从 google protobuf 消息中的属性名称查找消息类型?

转载 作者:太空宇宙 更新时间:2023-11-04 12:36:24 34 4
gpt4 key购买 nike

我有如下定义的 protobuf 消息。我需要从属性名称中找到消息类型。例如,当输入为“cfgMsg”时,输出应为 ConfigMsg 或 CfgServerMsg.ConfigMsg(全名)。

message CfgServerMsg {
string name = 1;
ConfigMsg cfgMsg = 2;
}

message ConfigMsg {
string cfgName = 1;
uint32 msgId = 2;
}

我有以下代码。但是,这适用于定义明确的类型,如字符串、整数、 float 等,对于消息,它只打印“消息”作为输出。

我删除了一些代码,只提供了与这个问题相关的代码。所以这显然不是完整的代码。

google::protobuf::Message *modObj = new ModObj();

const google::protobuf::Descriptor *outModDesc
= modObj->GetDescriptor();
const Reflection *outModRefl = modObj->GetReflection();
const FieldDescriptor *field;

// Loop to iterate over all the fields
{
field = outModDesc->FindFieldByName(tmp_name);
std::string type = field->type_name();
std::cout << "Type:" << type << std::endl;
}

输出:类型:字符串类型:消息

但是,我想获取实际的消息类型,即“ConfigMsg”,而不仅仅是“消息”。 protobuf 是否有任何此类 API 可用?

我确实查看了此页面 https://developers.google.com/protocol-buffers/docs/reference/cpp/google.protobuf.descriptor#FileDescriptor.name.details彻底,但找不到任何有用的东西。

如果有人做过类似的事情或者知道这方面的一些事情,那将会很有用。

谢谢,

最佳答案

我从另一个小组那里得到了一些线索,我可以用 C++ 编写代码来获取实际的消息类型。在下面发布详细信息以帮助其他人。

google::protobuf::Message *modObj = new ModObj();

const google::protobuf::Descriptor *outModDesc
= modObj->GetDescriptor();
const Reflection *outModRefl = modObj->GetReflection();
const FieldDescriptor *field;

// Loop to iterate over all the fields
{
field = outModDesc->FindFieldByName(tmp_name);
std::string type = field->type_name();
std::cout << "Type:" << type << std::endl;

outField = outModDesc->FindFieldByName(tmp_name);
const google::protobuf::Descriptor* tmpDesc = outField->message_type();
std::string subMsgType = tmpDesc->name();
std::string fullMsgType = tmpDesc->full_name();
std::cout << " Type: " << subMsgType
<< ", Full Type: " << fullMsgType << std::endl;
}

代码输出:

Type: ConfigMsg, FullType: frrcfg.ConfigMsg

关于c++ - 如何从 google protobuf 消息中的属性名称查找消息类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56247392/

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