How to set an extension field of the message by using reflection in protobuffer

Viewed 385

How to set an extension field of the message in protobuffer? The code is like this:

message Header {
    optional string name = 1;
    extensions 2 to 10; 
}
message PbDirectiveHeader {
    extend Header {
        optional string message_id = 2;
    }
}
    PbDirectiveHeader header_msg;
    std::cout << "header_msg des : " << header_msg.GetDescriptor() << std::endl;
    const google::protobuf::FieldDescriptor* message_id_dec = header_msg.GetDescriptor()->FindExtensionByName("message_id");
    if (message_id_dec != nullptr) {
        std::cout << "header_msg message_id's des containing_type: " << message_id_dec->containing_type() << std::endl;
        header_msg.GetReflection()->SetString(&header_msg, message_id_dec, "123456");
        std::cout << "message_id:" << header_msg.GetReflection()->GetString(header_msg, message_id_dec) << std::endl;
    } else {
        std::cout << "header_msg message_id des is nullptr" << std::endl;
    }

the error message is :

[libprotobuf FATAL google/protobuf/generated_message_reflection.cc:86] Protocol Buffer reflection usage error:
...
Problem     : Field does not match message type.

If I use reflection to set the name field of Header message, there is no error, but if I turn to set the extension field of message_id, the error happens again. how to solve my problem?

1 Answers

I find a solution to solve my problem

    PbDirectiveHeader header_msg;
    Header header;
    std::cout << "header_msg des : " << header_msg.GetDescriptor() << std::endl;
    const google::protobuf::FieldDescriptor* message_id_dec = header_msg.GetDescriptor()->FindExtensionByName("message_id");
    if (message_id_dec != nullptr) {
        std::cout << "header_msg message_id's des containing_type: " << message_id_dec->containing_type() << std::endl;
        header.GetReflection()->SetString(&header, message_id_dec, "123456");
        std::cout << "message_id:" << header.GetReflection()->GetString(header, message_id_dec) << std::endl;
    } else {
        std::cout << "headermessage_id des is nullptr" << std::endl;
    }

Use extension message to find an extension field, then use the base message to set/get the extension field's value.

Related