ee2 ee2 - 10 months ago 81
C++ Question

Access protocol buffers extension fields

I am working with protocol buffers in C++. My message has only one extension range. And I want to access all the extension fields without knowing their name, using only their numbers. How can I do this??

message Base {
optional int32 id = 1;
extensions 1000 to 1999;

extend Base{
optional int32 id2 = 1000;

Up till now, I have obtained ExtensionRange.

const google::protobuf::Descriptor::ExtensionRange* rng = desc->extension_range(0);
std::cerr << "rng " << rng->start << " " << rng->end << std::endl;

But I donot know to to get the
of the extensions.

There is one weird thing and that is
is returning 0. Although I have used extension in my .proto file. Similarly FindExtensionBy[Name/number] are not working as expected?

ee2 ee2
Answer Source

I found a solution using reflection.

const Reflection* ref = message_.GetReflection(); 
const FieldDescriptor* cfield = ref->FindKnownExtensionByNumber(33);

std::cerr << "cfield->name() " << cfield->name() << std::endl;

Now my existing solution will be to loop for all the numbers in extension range and get the required Fielddescriptors of the extensions.

I am still waiting for any better/different solution, you guys.