c++protobuf-c

How to read protobuf FileOptions in C++?


In the Google proto3 examples they show both global and nested custom options, including:

extend google.protobuf.FileOptions {
  string my_file_option = 1001;
}
option (my_file_option) = "hello file!";

and

extend google.protobuf.MessageOptions {
  optional string my_option = 51234;
}
message MyMessage {
  option (my_option) = "Hello world!";
}

The example code for C++ shows how to read the MyMessage.my_option field using GetExtension on the Message object, but not how to read the global option "my_file_option".

So in C++, how would I read the contents of "my_file_option"?


Solution

  • To get the proto's options rather than a Message, you need to load the proto from the DescriptorPool

    // Create descriptor pool of all loaded protos
    google::protobuf::DescriptorPool descriptorPool(google::protobuf::DescriptorPool::generated_pool());
    // Find specific proto file you want the options from
    const google::protobuf::FileDescriptor *file = descriptorPool.FindFileByName("my_proto.proto");
    // Fetch the options from the proto's FileDescriptor
    const google::protobuf::FileOptions options = file->options();
    // Get the contents of the specific extension (can also search by name)
    std::string service = options.GetExtension(my_proto::my_file_option);
    

    service will contain "hello file!"