首页 技术 正文
技术 2022年11月9日
0 收藏 883 点赞 2,793 浏览 1793 个字

之前写了《Protobuf 动态加载 .proto 文件并操作 Message》。除了直接读取 .proto 文件之外,还有一种类似的方法。先把 .proto 文件编译成 .pb 文件,再读取 .pb 文件。这种方法虽然比直接读取 .proto 多了一步,但是在运行期加载更快。

仍然使用之前的的 .proto 文件作为示例。使用 protoc.proto 文件编译为 .pb 文件。

./3rdparty/bin/protoc -I./proto -oaddressbook.pb --include_imports ./proto/addressbook.proto

注意,这里有两个 .proto 文件,应该选择没有被依赖的的 .proto 文件作为参数,并且添加 --include_imports 选项。这样,所有 .proto 文件及其依赖的 .proto 文件都被编进同一个 .pb 文件。

#include <iostream>
#include <fstream>
#include <google/protobuf/dynamic_message.h>
#include <google/protobuf/util/json_util.h>
#include <google/protobuf/descriptor.pb.h>using namespace google::protobuf;int main()
{
std::ifstream pb_file("./addressbook.pb", std::ios::binary);
if (!pb_file.is_open())
{
return -1;
} FileDescriptorSet file_descriptor_set;
if (!file_descriptor_set.ParseFromIstream(&pb_file)) {
return -1;
} DescriptorPool pool;
for (int i = 0; i < file_descriptor_set.file_size(); ++i) {
pool.BuildFile(file_descriptor_set.file(i));
} const Descriptor* person_descriptor = pool.FindMessageTypeByName("tutorial.Person"); DynamicMessageFactory message_factory;
const Message* default_person = message_factory.GetPrototype(person_descriptor);
Message* person = default_person->New(); const Reflection* reflection = person->GetReflection();
reflection->SetString(person, person_descriptor->FindFieldByName("name"), "abc");
reflection->SetInt32(person, person_descriptor->FindFieldByName("id"), 123456);
reflection->SetString(person, person_descriptor->FindFieldByName("email"), "abc@163.com"); util::JsonPrintOptions json_options;
json_options.add_whitespace = true;
json_options.always_print_primitive_fields = true;
json_options.preserve_proto_field_names = true;
std::string output;
util::MessageToJsonString(*person, &output, json_options);
std::cout << "====== Person data ======" << std::endl;
std::cout << output; delete person;
}

输出

====== Person data ======
{
"name": "abc",
"id": 123456,
"email": "abc@163.com",
"phones": []
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,088
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,564
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,412
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,185
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,822
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,905