1. 首页
  2. IT教程

动态读取protobuf数据

动态读取protobuf数据

1.流程

protobuf 版本3.12.1

  1. 使用Importer 动态读入proto文件原型
  2. 获取DescriptorPool
  3. 使用Message名称获取对应的Prototype
  4. 使用DynamicMessageFactory 生产Message
  5. 使用Message 读取Protobuf数据

2. test.proto

    message Test {
        optional string name = 1;
    }

3.简单举例

        Importer import(&tree, nullptr);
        // 可以加载多个文件(依赖)
        import.Import("/path/test.proto");
        import.Import("/path/other.proto");

        auto pool = import.pool();
        auto desc = pool->FindFileByName("test.proto");
        google::protobuf::DynamicMessageFactory factory;
        const google::protobuf::Message *prototype_msg = factory.GetPrototype("Test"); 
        auto instance = prototype_msg->New();
        instance->ParseFromString(contents);

原创文章,作者:夜风博客,如若转载,请注明出处:https://www.homedt.net/106158.html