C ++ Protobuf:如何遍历消息字段? [英] c++ protobuf: how to iterate through fields of message?

查看:148
本文介绍了C ++ Protobuf:如何遍历消息字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是protobuf的新手,但我坚持执行简单的任务:我需要遍历message字段并检查其类型.如果类型为message,则将对此消息进行递归操作.

I'm new to protobuf and I'm stuck with simple task: I need to iterate through fields of message and check it's type. If type is message I will do same recursively for this message.

例如,我有这样的消息:

For example, I have such messages:

package MyTool;

message Configuration {
    required GloablSettings         globalSettings  = 1;
    optional string                 option1         = 2;
    optional int32                  option2         = 3;
    optional bool                   option3         = 4;

}

message GloablSettings {
    required bool                   option1         = 1;
    required bool                   option2         = 2;
    required bool                   option3         = 3;
}

现在,要显式访问C ++中的字段值,我可以这样做:

Now, to explicitly access a field value in C++ I can do this:

MyTool::Configuration config;
fstream input("config", ios::in | ios::binary);
config.ParseFromIstream(&input);

bool option1val = config.globalSettings().option1();
bool option2val = config.globalSettings().option2();

,依此类推.这种方法在有大量字段的情况下不方便.

and so on. This approach is not convenient in case when have big amount of fields.

我可以通过迭代来做到这一点并获取字段的名称和类型吗?我知道有个描述符类型,有些叫做 reflection ,但是我的尝试没有成功.可能的话,有人可以给我示例代码吗?

Can I do this with iteration and get field's name and type? I know there are descriptors of type and somewhat called reflection, but I didn't have success in my attempts. Can some one give me example of code if it's possible?

谢谢!

推荐答案

看看Protobuf库如何实现 TextFormat :: Printer 类,该类使用描述符和反射来遍历字段和将它们转换为文本:

Take a look at how the Protobuf library implements the TextFormat::Printer class, which uses descriptors and reflection to iterate over fields and convert them to text:

https://github.com/google/protobuf/blob/master/src/google/protobuf/text_format.cc#L1473

这篇关于C ++ Protobuf:如何遍历消息字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆