我是protobuf的新手,我坚持简单的任务:我需要迭代消息字段并检查它的类型.如果类型是消息,我将递归地执行此消息.
@H_404_2@例如,我有这样的消息:
有人可以给我代码的例子吗? @H_404_2@谢谢!
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; }@H_404_2@现在,要明确地访问C中的字段值,我可以这样做:
MyTool::Configuration config; fstream input("config",ios::in | ios::binary); config.ParseFromIstream(&input); bool option1val = config.globalSettings().option1(); bool option2val = config.globalSettings().option2();@H_404_2@等等.如果有大量的字段,这种方法是不方便的. @H_404_2@我可以通过迭代来做到这一点,并获得字段的名称和类型?我知道有类型的描述,有点叫反思,但我的尝试没有成功.
有人可以给我代码的例子吗? @H_404_2@谢谢!
解决方法
看看Protobuf库如何实现TextFormat :: Printer类,它使用描述符和反射来迭代字段并将其转换为文本:
@H_404_2@https://github.com/google/protobuf/blob/master/src/google/protobuf/text_format.cc#L1473