Enrique Avina
Enrique Avina

Reputation: 1013

Get enum values using reflection google protobuf

Support I have an enum in a .proto file such as:

enum My_Types
{
  my_types_a = 0;

  my_types_b = 1;

  my_types_c = 2;

}

I want to generate an EnumDescriptor so that I can can reference values from this enum, but I must use the Google Reflection APIs . When using the protobuf compiled version of the .proto file, I would be able to say My_Types_descriptor() to get the EnumDescriptor, but how would I do this using reflection? The same would apply for EnumValueDescriptor which can describe a particular enum constant.

Given a DescriptorPool, how can I use reflection to achieve this? I believe this API could help, but I do not know how to use it.

Upvotes: 1

Views: 2944

Answers (2)

Enrique Avina
Enrique Avina

Reputation: 1013

What I as looking for was this:

const EnumDescriptor* enum_desc = Pool->FindEnumTypeByName(custom_type);

Where Pool is a google::protobuf::DescripterPool representing the definitions or all the message types and enum described by your protofiles. Once you have the EnumDescriptor, then you can use your reflection instance to say reflection->Getint32() (or whatever other type you expect) and say

const EnumValueDescriptor* enum_value_desc = enum_desc->FindValueByNumber(value);

This is give you the value of your enum.

Upvotes: 1

Bar Stool
Bar Stool

Reputation: 620

Do you mean you want to be able to do what EnumDescriptor does, without generating "Reflection code/data" at compile time to do so? I do not think there is a way to do this. Its a bit confusing what you mean by must use Reflection. Really, EnumDescriptor is using the C++ version of reflection.

Reflection by default is not available in c++. So if you want it, you have to write your owner parser (like protobuf) or write some magical macro/template code (like this SO answer) to generate the needed data for reflection. You just cant use reflection, you need the metadata about the class's/enums.

Perhaps I could add more if you clarify what you need to do and why?

Upvotes: 0

Related Questions