主要介绍下protocol buffer的基本使用流程。
平台:ubuntu14.04LTS
前提:已经安装完成protocol buffer
输出:C++格式(其他还有python格式 ,java格式)
可以分为几步:
一、根据自己需要,写一个protocol buffer的描述文件,后缀名为.proto,就是 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;
}
在终端执行以下命令 protoc msg.proto --cpp_out=.
注意:1、以上命令中 protoc 是命令
如果
所在文件夹和终端定位的文件夹相同,则不用写路径,否则,可能要写上msg.proto
的文件路径 xxx/xxx/xx/msg.protomsg.proto
2、
是指C++格式,输出Python格式则为--cpp_out
--python_out
3、命令中的等号(=)两端不要有空格,注意等号右边有个点(.)是必须的。
执行上述命令后,
msg.pb.h和msg.pb.cc //就是windows里的.h文件和.cpp文件
的同目录下会生产两个文件,msg.proto
注意:
msg.pb.cc
文件中会包含msg.pb.h
头文件,这个头文件要根据你的路径来写,自己生成的文件中写的路径不一定对。
二、
新建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
运行。
上述中,一定要注意终端所在目录,和你要执行的目录,和文件中包含的头文件等,路径是否对应。