Home > Net >  How to get a field object using its name in proto3
How to get a field object using its name in proto3

Time:11-11

I am migrating schemas from proto2 to proto3 syntax. I want to eliminate extensions as they are not supported. Is it possible to get an object using a field name in proto3, similar to what MutableExtension does in proto2.

For example,

Schema in proto2 syntax

message Foo {
  message Bar {
    unint32 a = 1;
  }
  extend Foo {
    Bar b = 1;
  }
}

C

Foo::Bar b_val = foo.MutableExtension(Foo::b);

Now in proto3, I could do this:

syntax="proto3";
message Foo {
  message Bar {
    unint32 a = 1;
  }
  Bar b = 1;
}

C code:

Foo::Bar b_val = foo.mutable_b();

However, I want to use the name Foo::b to get a Foo::Bar object. Is there a way to do this?

CodePudding user response:

It's not clear why you need this but what you are asking for is kinda feasible.

Foo::b is a garden variety member function, which means that &Foo::b is a regular pointer-to-member-function.

So you can use it as such using the regular c syntax for these entities:

auto b_ref = &Foo::b;

Foo::Bar b_val = (foo.*b_ref)();
  • Related