一、下载ProtocolBuffer、CMake
先去官网下载:ProtocolBuffer官网、CMake官网
我这里用的是protobuf-cpp-3.17.3.zip、cmake-3.18.2-win64-x64
二、编译ProtocolBuffer
解压protobuf-cpp-3.17.3.zip,打开cmake-3.18.2-win64-x64\bin\cmake-gui.exe,选择目录;
选择对应的版本和平台;
点击Generate,构建vs项目
打开protobuf_32\protobuf.sln项目,选择解决方案,点击生成得到libprotobufd.lib、libprotocd.lib、protoc.exe文件;
点击protobuf_32\extract_includes.bat,生成include文件夹;
三、新建项目测试ProtocolBuffer
新建hello.proto文件,复制下边的代码保存
syntax = "proto3";
package tutorial;
message Hello{
string say = 1;
}
当前hello.proto目录下打开cmd,执行protoc --cpp_out=./ hello.proto,得到hello.pb.h、hello.pb.cc文件;
vs新建控制台项目,添加include、lib文件夹,hello.pb.h、hello.pb.cc到项目中,vs中右键配置项目属性;
将下面代码拷贝到ProtobufTest32.cpp文件中保存,点击生成,运行;
#include <iostream>
#include <fstream>
#include <string>
#include "hello.pb.h"
using namespace std;
int main() {
tutorial::Hello hi;
hi.set_say("Hello World");
// 序列化
string str;
hi.SerializeToString(&str);
cout << "序列化后:" << str << endl;
// 反序列化
tutorial::Hello ha;
if (!ha.ParseFromString(str))
{
cerr << "failed." << endl;
return -1;
}
cout << "反序列化:" << ha.say() << endl;
google::protobuf::ShutdownProtobufLibrary();
return 0;
}
运行结果: