ProtoBuf的使用

简介:
在这里插入图片描述

1.生成vs工程

打开cmake:

选择protobuf下的cmake路径为源码路径,新建文件夹protobuf_win为生成路径。

点击Configure弹出选择vs版本的对话框
在这里插入图片描述

2.编译protobuf

打开vs工程,分别编译 libprotobuf和protoc这两个项目:生成libprotobufd.lib、libprotocd.lib和protoc.exe

5.生成***.cc和****.h文件

protobuf使用需要先把消息定义好,然后编译成自己的API,加入到自己的工程中使用。

(1)先编写myproto.proto文件: https://www.ibm.com/developerworks/cn/linux/l-cn-gpb/

syntax = “proto2”;
package mypb;
message helloworld
{
required int32 id = 1;
required string str = 2;
optional int32 opt=3;
}
package 名字叫做 mypb,定义了一个消息 helloworld,该消息有三个成员,类型为 int32 的 id,另一个为类型为 string 的成员 str。opt 是一个可选的成员,即消息中可以不包含该成员。

(2)编译myproto.proto文件:

可以使用dos窗口,进入到当前目录,执行:
在这里插入图片描述
–cpp_out是输出路径(./为当前路径),其他选项可以使用protoc --help查看

生成文件如下:
在这里插入图片描述

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include "myproto.pb.h"
 
int main(void)
{
	//消息封装
	mypb::helloworld in_msg;
	{
		in_msg.set_id(888);
		in_msg.set_str("helloworld");
		std::fstream output("./hello.log", 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;
		}
	}
	
	//消息解析
	mypb::helloworld out_msg;
	{
		std::fstream input("./hello.log", std::ios::in | std::ios::binary);
		if (!out_msg.ParseFromIstream(&input)) {
			std::cerr << "failed to parse" << std::endl;
			return -1;
		}
		std::cout << out_msg.id() << std::endl;
		std::cout << out_msg.str() << std::endl;
	}
		
	
	getchar();
	return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值