Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 Fielddescriptor* of the extensions.

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

like image 910
v78 Avatar asked Oct 04 '16 11:10

v78


People also ask

What are Protobuf extensions?

Extension (protobuf v0. 11.0) Extensions let you set extra fields for previously defined messages(even for messages in other packages) without changing the original message.

What is the difference between proto2 and proto3?

Proto3 is the latest version of Protocol Buffers and includes the following changes from proto2: Field presence, also known as hasField , is removed by default for primitive fields. An unset primitive field has a language-defined default value.

What are Protocol Buffers used for?

Protocol buffers provide a language-neutral, platform-neutral, extensible mechanism for serializing structured data in a forward-compatible and backward-compatible way. It's like JSON, except it's smaller and faster, and it generates native language bindings.

Can Protobuf fields be null?

Protobuf treats strings as primitive types and therefore they can not be null. Instead of checking if the string is not null use standard libraries, like apache commons, to check if the string is not blank. This is clear that the value will be inserted if the value is not blank.


1 Answers

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.

like image 180
v78 Avatar answered Oct 27 '22 08:10

v78