一、环境的安装
到github下载protobuf-cpp的包和protoc-win64的包
Release Protocol Buffers v3.7.1 · protocolbuffers/protobuf · GitHub
1.1 对于protoc-win64的包
将其解压,放到喜欢的路径下,然后将该路径加到系统环境变量中,接着可以用cmd测试一下,protoc命令是否可用
上图表示可以用,如果不可以用,重启一下cmd,如果还是不行,自行百度了
1.2对于protobuf-cpp的包
解压到路径,然后用cmake完成Configure,,Generate,,Open Project(不会的自行百度)
用vs2019(或者其他版本)分别编译libprotobuf,protoc,libprotoc这三个
编译完成后,在目标目录下找到相应的版本,我用的release模式
将release中这四个的拷贝到一个新的文件夹lib中
再新建一个include文件夹将解压出来的包中的src文件夹中的google文件夹拷贝进去
最后一步,将lib文件中的dll文件拷贝到C:\Windows\System32中(防止运行程序找不到动态库)
至此,我们得到了两个文件夹,分别是lib和include,这两个文件可以放在固定的地方,也可以跟随项目,拷贝到项目文件夹中去(我是拷贝到项目中去的)
二、protobuf测试
创建一个vs项目,在项目文件夹中新建一个msg.proto文件,内容如下
syntax="proto3";
package lm;
message helloworld
{
int32 id = 1; // ID
string str = 2; // str
int32 opt = 3; //optional field
}
接着打开cmd用protoc执行此文件,指令如下,只需要将文件路径填写上去,和文件名字填写上去就可以
//SRC_DIR .proto文件存放目录
//--cpp_out 指示编译器生成C++代码,DST_DIR为生成文件存放目录
//game.proto 待编译的协议文件
protoc -I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/game.proto
完成后会得到两个文件,分别是msg.pb.h和msg.pb.cc
至此,完成了准备工作,接着打开vs项目,添加这两个文件到项目中以及做一些其他配置工作,如下
添加三个文件,main.cpp内容如下
#include "msg.pb.h"
#include <fstream>
#include <iostream>
using namespace std;
void ListMsg(const lm::helloworld& msg)
{
cout << msg.id() << endl;
cout << msg.str() << endl;
}
void test_write()
{
lm::helloworld msg1;
msg1.set_id(101);
msg1.set_str("hello");
fstream output("./log", ios::out | ios::trunc | ios::binary);
if (!msg1.SerializeToOstream(&output))
{
cerr << "Failed to write msg." << endl; return ;
}
}
void test_read()
{
lm::helloworld msg1;
{
fstream input("./log", ios::in | ios::binary);
if (!msg1.ParseFromIstream(&input)) {
cerr << "Failed to parse address book." << endl;
return ;
}
}
ListMsg(msg1);
}
int main(void)
{
test_write();
test_read();
return 0;
}
vs配置属性有以下,不配置可能会出错
根据生成的protobuf库相应配置,我是release x64版本,将我们生成的lib和include添加到这两个路径
预处理加上 PROTOBUF_USE_DLLS,否则大量报错
链接器输入中添加libprotobuf.lib和libprotoc.lib
至此配置完成,直接运行看结果
至此结束