Setting field of a Message inside Message Protobuf
Asked Answered
G

2

14

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 ?

Gerundive answered 5/11, 2012 at 10:25 Comment(1)
Can someone add the translation in english for non-spanish speakers?Bibbs
A
16

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.

Assoil answered 5/11, 2012 at 10:43 Comment(0)
S
1

In case you'd want to set all the fields at once, you can use set_allocated_foo() along with copy or move constructors, e.g.,

this->cbmsg->set_allocated_repomessage(new RepoMessage(repomessage));
Stiver answered 28/9, 2023 at 16:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.