WIN环境 下载与安装
下载
https://github.com/protocolbuffers/protobuf/releases
官方git地址,目前最新的是3.8版本;
我是c++环境,选择cpp下载包
protobuf-cpp-3.8.0.tar.gz
安装
解压后,打开protobuf-3.8.0\README.md 文件,里边明确指出了c++的安装参考文件:
Protocol Compiler Installation
The protocol compiler is written in C++. If you are using C++, please follow the C++ Installation Instructions to install protoc along with the C++ runtime.
链到如下文件:
protobuf-3.8.0\src\README.md
区分linux和win的安装方法;win又链到了另外一个文件:
To build from source using Microsoft Visual C++, see cmake/README.md.
protobuf-3.8.0\cmake\README.md
执行完最后一步安装后,会再并行目录生成一个\install文件夹,里边包含了win要用的库、头文件、pb转换工具 三项;
官方API指南
https://developers.google.cn/protocol-buffers/docs/reference/overview
protocol buffer 转json 方案
转json功能官方API
https://developers.google.cn/protocol-buffers/docs/reference/cpp/google.protobuf.util.json_util
.proto 文件编译方法及编译类生成的成员方法规律
https://developers.google.cn/protocol-buffers/docs/reference/cpp-generated
TMT.proto文件示例
syntax = "proto3";
package cmu_cmdp;
message CMU_TMt
{
uint32 main_type = 1;
uint32 sub_type = 2;
uint32 mcu_id = 3;
uint32 eqp_id = 4;
uint32 confdri_id = 5;
uint32 conf_idx = 6;
}
message CMU_TBasicConfInfo
{
CMU_TMt speaker = 1;
CMU_TMt chairman = 2;
string e164str = 4;
repeated CMU_TMt tmtarr = 6;
reserved 3,5;
}
把.proto文件转成c++的.h.cc文件
启用cmd,调用安装时生成的protobuf.exe 可执行文件,执行命令 protobuf.exe --cpp_out=./ TMT.proto,会在本目录下生成对应的TMt.pb.h、TMt.pb.cc
c++实例代码
#include "TMt.pb.h" // 包含.proto生成的头文件
#include <google/protobuf/util/json_util.h> // 要使用转json功能,需要包该头文件
using namespace std;
using namespace google::protobuf::util; // 引入命名空间
using namespace cmu_cmdp;
int main()
{
CMU_TMt tmt1;
tmt1.set_conf_idx(1);
tmt1.set_eqp_id(11);
tmt1.set_main_type(9);
tmt1.set_confdri_id(3);
tmt1.set_mcu_id(33);
tmt1.set_sub_type(7);
CMU_TMt tmt2;
tmt2.set_conf_idx(2);
tmt2.set_eqp_id(22);
tmt2.set_main_type(22);
tmt2.set_confdri_id(2);
tmt2.set_mcu_id(22);
tmt2.set_sub_type(2);
CMU_TBasicConfInfo cSimConfInfo;
cSimConfInfo.set_allocated_speaker(&tmt1);
cSimConfInfo.set_allocated_chairman(&tmt2);
cSimConfInfo.set_e164str("0512110");
CMU_TMt *ptmt = cSimConfInfo.add_tmtarr();
*ptmt = tmt1;
ptmt = cSimConfInfo.add_tmtarr();
*ptmt = tmt2;
std::string strmsg;
MessageToJsonString(cSimConfInfo, &strmsg); // 结构体转json
cout << strmsg.c_str() << endl;
CMU_TBasicConfInfo cSimConfInfo2;
JsonStringToMessage(strmsg, &cSimConfInfo2); // json 反转结构体
cout << cSimConfInfo2.speaker().mcu_id() << endl;
cout << cSimConfInfo2.chairman().mcu_id() << endl;
return 0;
}
输出结果
{"speaker":{"mainType":9,"subType":7,"mcuId":33,"eqpId":11,"confdriId":3,"confIdx":1},"chairman":{"mainType":22,"subType":2,"mcuId":22,"eqpId":22,"confdriId":2,"confIdx":2},"e164str":"0512110","tmtarr":[{"mainType":9,"subType":7,"mcuId":33,"eqpId":11,"confdriId":3,"confIdx":1},{"mainType":22,"subType":2,"mcuId":22,"eqpId":22,"confdriId":2,"confIdx":2}]}
33
22