简体   繁体   中英

How to cast a google::protobuf::Message* to concrete protocol-buffer object

Proto defined as below:

/*
Message Test {
    int32 a = 1;
    repeated int64 b = 2;
};
*/

c++ code below:

// msg is a `Test` type pointer
int32_t get_a(google::protobuf::Message* msg) {
    Test t1;
    // what is the most efficient way to convert `msg` to `t1`
    return t1.a();
}

ParseFromString might be too slow as far as I know. Is reflection slow? What's the best way to solve this problem?

From the official dochttps://developers.google.com/protocol-buffers/docs/cpptutorial , you can do this:

Test t;
t.set_a(1);
t.add_b(2);
std::string data;
t.SerializeToString(&data);

Test t1;
t1.ParseFromString(&input); // or ParseFromIstream if you have a stream

In other words, you can directly parse that message into your Test object.

The high-level idea is that, protobuf is strongly typed and make heavy use of code generators . So with all those auto-generated code, you can happily parse the data into your struct/class!

Just cast it to Test* :

int32_t get_a(google::protobuf::Message* msg) {
    auto *t1 = dynamic_cast<Test*>(msg);
    if (t1 == nullptr)
        throw runtime_error("not of type Test");
    return t1->a();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM