Roy Huang
Roy Huang

Reputation: 629

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?

Upvotes: 0

Views: 2570

Answers (2)

for_stack
for_stack

Reputation: 22946

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();
}

Upvotes: 1

ch271828n
ch271828n

Reputation: 17597

From the official doc https://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!

Upvotes: 1

Related Questions