Search code examples
c++nestedprotocol-buffers

Setting field of a Message inside Message Protobuf


I have the following protobuf definition:

message CBMessage {
  
    required int32 type = 1; //defines the kind of message that we send
    optional RepoMessage repomessage = 2;
  
    message RepoMessage { 
        optional int32 nodeid = 1;
        optional int32 timestampsec = 2;
        optional int32 timestampmicrosec = 3;
    }
}

As you can note, the repomessage field is a field of the "outer" message CBMessage.

I would like to access nodeid field (of the "inner" message RepoMessage) in order to modify this parameter. So I create a CBMessage object:

CBTxMessages::CBMessage* cbmsg;
this->cbmsg = new CBTxMessages::CBMessage;

And I have tried to modify the nodeid field in this way:

this->cbmsg->repomessage().set_nodeid(message[0]);

Yet, I get the following error when I compile:

error: pasar ‘const CBTxMessages::CBMessage_RepoMessage’ como el argumento ‘this’ de ‘void CBTxMessages::CBMessage_RepoMessage::set_nodeid(google::protobuf::int32)’ descarta a los calificadores [-fpermissive]

(The error is in Spanish but I think that you can understand). A possible translation will be:

"the 'this' argument of 'void CBTxMessages :: CBMessage_RepoMessage :: set_nodeid (google :: protobuf :: int32)' discards the qualifiers")

I have investigated it and found that the problem is related to the fact that the "basic getter" of the repomessage field returns (repomessage()) is returned as const reference (thus it cannot be modified directly), but I do wish to modify it.

How can I solve this ?


Solution

  • Instead of

    this->cbmsg->repomessage().set_nodeid(message[0]);
    

    you'll need

    this->cbmsg->mutable_repomessage()->set_nodeid(message[0]);
    

    to set the repomessage field directly. repomessage() will return a const CBMessage_RepoMessage& that cannot be modified.