0

原型定义如下:

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

c++代码如下:

// 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据我所知,可能太慢了。反射慢吗?解决这个问题的最佳方法是什么?

4

2 回答 2

1

从官方文档https://developers.google.com/protocol-buffers/docs/cpptutorial,您可以这样做:

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

换句话说,您可以直接将该消息解析到您的 Test 对象中。

高级的想法是,protobuf 是强类型的并且大量使用代码生成器。因此,使用所有这些自动生成的代码,您可以愉快地将数据解析到您的结构/类中!

于 2020-12-22T11:59:15.033 回答
1

只需将其转换为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();
}
于 2020-12-23T06:29:18.423 回答