1.camke的安装和protobuf源码下载
略过,自行百度下载。
2.使用cmake编译protobuf源码。
3.测试生成的工具。
自行编写proto文件,文件后缀为.proto。
syntax="proto2";
package RingBind;
message MBUI_GetOrSetRingBinding
{
optional int32 hSeeion = 1;
optional int32 CircuitID = 2;
optional MBUI_RingBindingVec oRingBinding = 3;
}
message MBUI_RingBindingVec
{
repeated MBUI_RingBind oRingBind = 1;
}
message MBUI_RingBind
{
optional int32 iStartNeID = 1;
optional int32 iEndNeID = 2;
optional int32 iRingID = 3;
}
///////在上一步生成的protoc.exe目录下cmd运行 protoc.exe,protoc --cpp_out=./ test .proto,成功会生成两个文件test.pb.h和test.pb.cc。这两个文件就相当于脚本给你生成的一个类,在你的项目中直接添加现有项就可以。
参考文章:https://blog.csdn.net/hp_cpp/article/details/81561310
备注:本人参考参考原作者有一处设置不一样,即设置项目属性的运行库
4.工程测试代码。(简单项目,没写啥注释)
#include
#include
#include
#include "RingBind.pb.h"
using namespace std;
void InitRingBind(RingBind::MBUI_GetOrSetRingBinding &oGetOrSetRingBinding)
{
//为message的简单类型(int32,bool等)赋值
oGetOrSetRingBinding.set_hseeion(998);
oGetOrSetRingBinding.set_circuitid(15390);
//为内嵌的message分配内存,这里的内嵌message的类型类型像Vector(数组),pRingBindingVec类似数组的首地址
RingBind::MBUI_RingBindingVec *pRingBindingVec =
oGetOrSetRingBinding.mutable_oringbinding();
//为数组添加一个元素
RingBind::MBUI_RingBind *pRingBind = pRingBindingVec->add_oringbind();
//为数组的第一个元素赋值
pRingBind->set_istartneid(690);
pRingBind->set_iendneid(640);
pRingBind->set_iringid(181135);
}
void WriteRingBind2File(string &out, RingBind::MBUI_GetOrSetRingBinding &oGetOrSetRingBinding)
{
fstream file(out.c_str(), ios::out | ios::trunc | ios::binary);
if (!file.is_open())
{
cout << out.c_str() << " open failed" << endl;
return;
}
oGetOrSetRingBinding.SerializePartialToOstream(&file);
file.close();
}
void readRingBind2File(string &in, RingBind::MBUI_GetOrSetRingBinding &oGetOrSetRingBinding)
{
fstream file(in.c_str(), ios::in | ios::binary);
if (!file.is_open())
{
cout << in.c_str() << " open failed" << endl;
return;
}
//从文件中解析出对象信息输出
oGetOrSetRingBinding.ParseFromIstream(&file);
cout << "hseeion: " << oGetOrSetRingBinding.hseeion() << endl;
cout << "circuitid: " << oGetOrSetRingBinding.circuitid() << endl;
const RingBind::MBUI_RingBindingVec oRingBindVec =
oGetOrSetRingBinding.oringbinding();
for (int i = 0; i < oRingBindVec.oringbind_size()/*获取数组的大小*/; i++)
{
const RingBind::MBUI_RingBind oRingBind = oRingBindVec.oringbind(i);
cout << "istartneid: " << oRingBind.istartneid() << endl;
cout << "istartneid: " << oRingBind.iendneid() << endl;
cout << "istartneid: " << oRingBind.iringid() << endl;
}
file.close();
}
int main()
{
RingBind::MBUI_GetOrSetRingBinding oGetOrSetRingBinding;
InitRingBind(oGetOrSetRingBinding);
string FileName("ser.txt");
WriteRingBind2File(FileName, oGetOrSetRingBinding);
RingBind::MBUI_GetOrSetRingBinding rGetOrSetRingBinding;
readRingBind2File(FileName, rGetOrSetRingBinding);
system("pause");
return 0;
}
运行结果: