protobuf 安装 及 使用

文章中有不理解的地方 进群交流讨论服务器技术 可以加Q群397926909

1.下载protobuf

Releases · protocolbuffers/protobuf · GitHub

2.使用CMAKE编译 编译完成后 打开VS工程编译libprotobuf,protoc,libprotoc这三个

 3 编译生成后的下列文件

放到项目libs目录下

 4 拷贝google 文件放项目下的include文件夹里

 5 然后修改VS属性 如下图

ptorobuf安装完成

下面使用protobuf

1.ptorobuf的语法有如下

package 声明
.proto 文件以一个 package 声明开始。这个是为了防止不同项目之间的命名冲突。类似于c++的namespcae xxx

字段类型
消息(message)定义了。一个消息就是某些类型的字段的集合。许多标准的、简单的数据类型都可以用作字段类型,字段类型有如下

在这里插入图片描述

修饰符
字段都需要用以下之一的修饰符来修饰:

(1)required
必须提供字段值,否则对应的消息会被认为是“未初始化的”。required 的字段与 optional 字段类似,为了兼容性 基本使用optional了

(2)optional
字段值指定与否都可以。如果没有指定一个 optional 的字段值,它就会使用默认值。

(3)repeated
字段会重复 N 次(N 可以为 0)
2.创建一个Account.proto文件里面内容为:

例子为:

syntax = "proto2";  //选择proto语法  有proto3
package myprotobuf; //命名空间
message helloworld //包名
{
    required int32 id = 1;
    optional string name = 2;
    optional string password=3;
}

3.把Account.proto文件放到lib下 cmd命令下使用 protoc.exe --cpp_out=./ Account.proto命令后

 会生成Account.pb.cc  及 Account.pb.h文件

把Account.pb.cc文件添加到项目中

使用测试代码编译

#include <iostream>
#include <fstream>
#include <windows.h>
#include <Account.pb.h>
#include <string>

using namespace std;
int main(void)
{
	//消息封装
	
	myprotobuf::helloworld in_msg;
	{
		in_msg.set_id(888);
		string str = "我是中国人";   
		cout << sizeof(str);
		in_msg.set_name(nameencode);
		std::fstream output("./proto.text", std::ios::out | std::ios::trunc | std::ios::binary);
		if (!in_msg.SerializeToOstream(&output)) {
			std::cerr << "failed to serialize in_msg" << std::endl;
			return -1;
		}
	}

	//消息解析
	myprotobuf::helloworld out_msg;
	{
		std::fstream input("./proto.text", std::ios::in | std::ios::binary);
		if (!out_msg.ParseFromIstream(&input)) {
			std::cerr << "failed to parse" << std::endl;
			return -1;
		}
		
		string name = out_msg.name();
		std::cout << out_msg.id() << std::endl;
		std::cout << "解析后的数据转码后为:" << name << std::endl;
	}


	getchar();
	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值