lundi 3 août 2020

c++ protobuf oneof deserializing generically

Hi i am wondering if there is a generic way to de-serialize a message that has a oneof message. The oneof message will contain many other messages. Right now i can get it working using a switch statement on the case number and the calling the appropriate getter but if there is a generic way so that in the future i don't have to keep adding new cases.

I would like to eliminate the cases and have something generic where I could get the message type ie.(Exit) and call the correct getter. Is there a way to do it with reflection? I looked for examples online but couldn't find much.

//proto file:

    message AllClientMessages{
    oneof client_message
    {
        util.client.command Exit exit = 1
        util.client.command SendNew sendnew = 2
        util.client.command CancelAll cancelAll = 3
      //..... (more than 60 messages)
    }
}

//in my protobuilder class ( I get the buffer from the socket )

const std::unique_ptr<google::protobuf::Message> ProtoBuilder::deserialize(char* buf)
{
    AllClientMessages clientMsg;
    clientMsg.ParseFromString(buf);

    switch(clientMsg.client_message_case())
    {
        case AllClientMessages::kExitFieldNumber: //generate enums
            return make_unique<Exit>(clientMsg.exit());

        case AllClientMessages::kSendNewFieldNumber:
            return make_unique<SendNew>(clientMsg.sendnew());

 //i access the getter and return unique_ptr to base protobuf Message.
        ... i do this for each case
    }
}




Aucun commentaire:

Enregistrer un commentaire