如何使用 protobuf 描述符来读取枚举

How to use protobuf descriptor to read enums

本文关键字:读取 枚举 描述 何使用 protobuf      更新时间:2023-10-16

假设我有一个 .proto 文件:

message Foo {
optional int32 x = 1;
enum y {
MOBILE = 0;
HOME = 1;
}
optional string z = 3;
}

然后我有这个C++代码,它打印所有类型:

const Reflection *refl = Foo.GetReflection(); 
const Descriptor *desc = Foo.GetDescriptor();
int fieldCount = desc->field_count();
for(int i=0;i<fieldCount;i++){
const FieldDescriptor *field = desc->field(i);
cout  << field->name().c_str() << " the type is " 
<<field->type_name()<< ": Type Number "<< field->type() <<endl;
if(field->type()==FieldDescriptor::TYPE_ENUM){
//do something
}

然后输出为:

x the type is int32: Type Number 5
z the type is string: Type Number 9

如输出所示,枚举被跳过,我如何让字段描述符也解析枚举?

您没有枚举类型的字段,您只定义了一个类型。因此,对字段的迭代不会产生与枚举相关的任何内容。

如果添加给定类型的字段,您将在那里看到您的枚举。