Groups keyboard shortcuts have been updated
Dismiss
See shortcuts

add a google.protobuf.Any field through reflection

49 views
Skip to first unread message

Phil Dougherty

unread,
Sep 26, 2024, 1:26:59 AM9/26/24
to Protocol Buffers
I'm trying to dynamically populate an Any message, and cannot figure out how I should do it. The code I'm currently working with is this:

google::protobuf::Message* dstmessage; //some existing message with a google.protobuf.Any in its "myAnyField" member I would like to fill out
const google::protobuf::Descriptor* dstdescriptor = dstmessage->GetDescriptor();
const google::protobuf::Reflection* dstreflection = dstmessage->GetReflection();
const google::protobuf::
FieldDescriptor* dstfield = dstdescriptor->FindFieldByName("myAnyField");
google::protobuf::Message* myAnyMessage = dstreflection->MutableMessage(
dstmessage, dstfield);
//note that here, myAnyMessage->GetDescriptor()->full_name() == "google.protobuf.Any"

google::protobuf::Any* myAnyContent = new google::protobuf::Any();
//assume myAnyContent is filled out with data here

google::protobuf::Any* myAnyField = google::protobuf::DynamicCastToGenerated<google::protobuf::Any>(myAnyMessage);
//myAnyField is null here! the cast failed! why?

myAnyField->MergeFrom(*myAnyContent);

Any tips?

Phil Dougherty

unread,
Sep 26, 2024, 11:50:32 AM9/26/24
to Protocol Buffers
I believe the issue has come down to, I'm finding a different "google/protobuf/any.proto" indirectly via the Importer than I am compiling against (I've used protoc to generate any.pb.cc and then compiled that alongside my source). how can I make sure these are the same version?

Phil Dougherty

unread,
Sep 26, 2024, 4:43:17 PM9/26/24
to Protocol Buffers
couldn't figure this out. the workaround I came up with was:
- populate the message by setting its "type_url" and "value" fields explicitly with the reflection API
- populate an any via its .set_type_url()/.set_value() functions with content harvested from the message via its reflection "getString" on those fields

tl;dr: manually piece-wise copy the values from one form to the other
Reply all
Reply to author
Forward
0 new messages