一、Protobuf 安装
- 安装protobuf
tar -xvf protobuf
cd protobuf
./autogen.sh生成configure
./configure --prefix = /usr/local/protobuf
make
make check
make install
- 安装完成,下面配置:
- vi /etc/profile,添加
export PATH=$PATH:/usr/local/protobuf/bin/
export PKG_CONFIG_PATH=/usr/local/protobuf/lib/pkgconfig/
保存执行,source /etc/profile。同时在~/.profile中添加上面两行代码,否则会出现登录 用户找不到protoc命令。
配置动态链接库
(2)vim /etc/ld.so.conf,在文件中添加/usr/local/protobuf/lib(注意: 在新行处添加), 然后执行命令: ldconfig
二、Protobuf 使用(c++)
- proto结构格式a.proto
message PermitGwPolicys{
repeated PermitGwPolicy permitGwPolicy = 1; //策略
repeated PermitGwWhiteInfo permitGwWhiteInfo = 2;//白名单
}
message PermitGwPolicy{
optional string permitGwPolicyId=1; //准入策略ID
optional string applySystemIp=2; //应用系统地址
optional string applySystemPort=3; //应用系统端口
optional string responseAction=4; //响应动作
repeated ExtendField extendFieldList = 5; //扩展字段
}
message PermitGwWhiteInfo{
optional string startIp=1; //起始IP
optional string endIp=2; //结束IP
optional string permitGwPolicyId=3; //策略ID
repeated ExtendField extendFieldList = 4; //扩展字段
}
- 编译成a.pb.h a.pb.cc
protoc --cpp_out=./ a.proto 在当前目录下生成a.pb.h a.pb.c
- 使用
#include <iostream>
#include <stdio.h>
#include <fstream>
#include <string>
#include "permitGwPolicyInfo.pb.h"
using namespace std;
//读取
int main()
{
fstream input("a.proto",ios::in | ios::binary);
PermitGwPolicys a1;
a1.ParseFromIstream(&input);
cout<<"=====permitgwpolicy====="<<a1.permitgwpolicy_size()<<endl;
for(int i=0;i < a1.permitgwpolicy_size();i++)
{
cout<<a1.permitgwpolicy(i).permitgwpolicyid()<<endl;
cout<<a1.permitgwpolicy(i).applysystemip()<<endl;
cout<<a1.permitgwpolicy(i).applysystemport()<<endl;
}
cout<<"=====permitgwwhiteInfo====="<<a1.permitgwwhiteinfo_size()<<endl;
for(int j = 0;j <a1.permitgwwhiteinfo_size();j++)
{
cout<<a1.permitgwwhiteinfo(j).startip()<<endl;
cout<<a1.permitgwwhiteinfo(j).endip()<<endl;
cout<<a1.permitgwwhiteinfo(j).permitgwpolicyid()<<endl;
}
return 0;
}
g++ -I /usr/local/protobuf/include/ a.pb.cc *.cpp `pkg-config --cflags --libs protobuf`
/usr/local/protobuf/ protobuf安装目录
` 键盘左上角,1的旁边 ~