Reputation: 1134
After a few hours, I still can not set a oneof
field in a clear (just created) protobuf message using reflection in c++.
I can obtain the needed OneOfDescriptor through the Descriptor of the message. But when I try to 'set' the oneof using Reflection, I found the real problem. There is only three function members related to OneOfDescriptor:
oneof
in the messageoneof
in the messageoneof
.So there is not a SetOneofFieldDescriptor
and if the oneof
in the message is not previously defined, using a mutable_XXXX
function member in the message, the GetOneofFieldDescriptor
returns nullptr
.
Therefore I am really stuck and any idea will be welcome.
Thanks in advance.
Upvotes: 1
Views: 4844
Reputation: 30494
You set it the same way you would set the field if it weren't part of a oneof
. Get a FieldDescriptor
from the message's Descriptor
and pass it to the appropriate SetXXX
method of the message's Reflection
.
Given a message like the following:
message Foo
{
oneof bar
{
int32 a = 1;
string b = 2;
}
}
You can set the a
member as follows:
#include "foo.pb.h"
int main()
{
Foo f;
const google::protobuf::Descriptor* d = f.GetDescriptor();
const google::protobuf::FieldDescriptor* a = d->FindFieldByName("a");
const google::protobuf::Reflection* r = f.GetReflection();
r->SetInt32(&f, a, 42);
}
Protobuf will take care of making sure any previously set members of the oneof
get unset as needed.
Upvotes: 3