Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Copy protobuf field to another protobuf in C++

We have the following protobuf definition

message SubMessage {
  optional string var_1 = 1;

  repeated string var_2 = 2;
}

message MainMessage {
  repeated Foo1 foo_1 = 1;

  repeated Foo2 foo_2 = 2;

  optional SubMessage foo_3 = 6;
}

When trying to merge this subproto as part of the main proto

 proto::MainMessage main_message_proto;
 proto::SubMessage submessage_proto;

 ...

 main_message_proto.MergeFrom(submessage_proto);

The following error occurs:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Tried to merge messages of different types

What’s the correct function to merge the information of the submessage as a field of the main message?

>Solution :

MergeFrom merges two messages of the same type. For example, if you had one MainMessage with its foo_1 field set and another with its foo_2 field set, you could merge them together and the result would be a message with both the foo_1 and foo_2 fields set.

But that’s not what you have here. You have a MainMessage and want to merge its SubMessage field with another SubMessage. To do that you need to call MergeMessage on foo_3:

main_message_proto.mutable_foo_3()->MergeFrom(submessage_proto);

If foo_3 is currently empty, then there’s no need to use MergeFrom. Simple assignment will do in that case:

*main_message_proto.mutable_foo_3() = submessage_proto;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading