proto文件内容如下:
syntax = "proto3";
message Person
{
int64 id = 1;
bytes name = 2;
string sex = 3;
int64 age = 4;
}
使用cmake生成的protoc.exe对proto文件进行编译,我的proto文件名称为:Person.proto
使用命令:
protoc .\Person.proto --cpp_out=./
生成的Person.pb.h以及Person.pb.cc文件路径与proto文件路径一致,在vs2022中创建空项目
将上面两个文件添加进项目中,修改项目属性,将cmake生成的头文件以及库添加,我是放在D盘中
然后修改c/c++下,预处理器,在预处理器定义中添加 PROTOBUF_USE_DLLS,如果这个地方没有添加,会在后序编译中报错
在编译过程中会出现“无法解析的外部命令”的错误,是因为缺少相关的依赖项,在属性-输入-附加依赖项中添加 libprotobufd.lib 即可
在Person.pb.h中会有一些地方报错,基本是宏定义错误,可以在头文件中添加如下内容:
#define PROTOBUF_NAMESPACE_OPEN \
namespace google \
{ \
namespace protobuf \
{
#define PROTOBUF_NAMESPACE_CLOSE \
} \
}
#define PROTOBUF_NAMESPACE_ID google::protobuf
#define PROTOBUF_CONSTEXPR
#define PROTOBUF_ATTRIBUTE_REINITIALIZES
#define PROTOBUF_NODISCARD [[nodiscard]]
#define PROTOBUF_ALWAYS_INLINE
using namespace google;
然后编写测试代码,进行序列化以及反序列化,如下:
#include <iostream>
#include "Person.pb.h"
using namespace std;
/*
message Person
{
int64 id = 1;
string name = 2;
string sex = 3;
int64 age = 4;
}
*/
int main()
{
//1.创建person对象,并且初始化
Person p;
p.set_id(1001);
p.set_name("路飞");
p.set_sex("man");
p.set_age(18);
//2.将person对象序列化 -- 字符串
string output;
p.SerializeToString(&output);
cout << "序列化后的数据是:" << output << endl;
//3.数据传输
//
//4.接收数据,解析(output) --解码
//4.1创建对象
Person p1;
//4.2解析
p1.ParseFromString(output);
//5.处理原始数据 -- 打印数据信息
cout << "id = " << p1.id() << endl;
cout << "name = " << p1.name() << endl;
cout << "sex = " << p1.sex() << endl;
cout << "age = " << p1.age() << endl;
system("pause");
return 0;
}
最后运行效果如下: