【protocol buff】protocol buffer 的使用方法

原文:https://blog.csdn.net/s9434/article/details/76632390

一、protocol buff的使用方法

1、安装protocol buff

2、写协议数据描述文件, xxx.proto  ,如:msg.proto:

package demo;   //相当于命名空间,std,cv等
message msg
{

	required int32 MsgType = 1;
	required string MsgInfo = 2;
	required string MsgFrom = 3;
	optional string opt = 4;
}

3、利用protoc.exe 将xxx.proto 转换成目标语言的 代码(提供了生成和解析协议数据的API)

在终端执行以下命令    protoc msg.proto --cpp_out=.                   

注意:1、以上命令中  protoc 是命令  
如果msg.proto所在文件夹和终端定位的文件夹相同,则不用写路径,否则,可能要写上msg.proto的文件路径
    xxx/xxx/xx/msg.proto
            2、--cpp_out是指C++格式,输出Python格式则为--python_out
            3、命令中的等号(=)两端不要有空格,注意等号右边有个点(.)是必须的。
执行上述命令后,msg.proto的同目录下会生产两个文件,msg.pb.h和msg.pb.cc 
 //就是windows里的.h文件和.cpp文件
注意:msg.pb.cc文件中会包含msg.pb.h头文件,这个头文件要根据你的路径来写,自己生成的文件中写的路径不一定对。
原文:https://blog.csdn.net/s9434/article/details/76632390 
 

4、将目标代码加入工程使用

新建C++源文件,本文命名为protobuf_test.cc。写入下列代码


#include "msg.pb.h"

#include <iostream>

#include <string>

using namespace std;

int main(int argc,char *argv[])

{

	demo::msg msg_test;

	msg_test.set_msgtype(1);

	msg_test.set_msginfo("I am a hongxing boy");

	msg_test.set_msgfrom("127.0.0.1");

	

	string In_data;

	msg_test.SerializeToString(&In_data);

	cout<<"format: "<<In_data<<endl;

 

	demo::msg msg_encoding;

	msg_encoding.ParseFromString(In_data);

	cout<<"msg type: "<<msg_encoding.msgtype()<<endl;

	cout<<"msg info: "<<msg_encoding.msginfo()<<endl;

	cout<<"msg from: "<<msg_encoding.msgfrom()<<endl;

	return 0;

}

完成后保存,可以在Vim中写,或eclipse中,完成后保存。
三、
在终端下执行g++ protobuff_test.cc msg.pb.cc -o main -lprotobuf -pthread命令进行编译,编译成功后执行./main运行。
上述中,一定要注意终端所在目录,和你要执行的目录,和文件中包含的头文件等,路径是否对应。

原文:https://blog.csdn.net/s9434/article/details/76632390 

扫描二维码关注公众号,回复: 5418039 查看本文章

猜你喜欢

转载自blog.csdn.net/bandaoyu/article/details/88084157