protocol buffer使用范例5

来源:互联网 发布:桌面切换软件 编辑:程序博客网 时间:2024/06/05 11:13

protocol buffer使用范例

1、创建.proto文件

首先创建自己的.proto文件

为了便于大家的理解,我创建了一个官方demo的变形体的.proto文件,名为person.proto

message Car {  required string engine = 1;  optional int32 punishment = 2;}message Person {  required string name = 1;  required int32 id = 2;  optional string email = 3;  enum PhoneType {    MOBILE = 0;    HOME = 1;    WORK = 2;  }  message PhoneNumber {    required string number = 1;    optional PhoneType type = 2 [default = HOME];  }  repeated PhoneNumber phone = 4;  optional Car owncar = 5 ;}
此文件包含了三种格式的描述符:required/optional/repeated。含string/int32/enum类型。以及外部message和内部message的使用。

2、生成cpp类文件

在.proto文件目录执行:

./protobuf-2.4.1/src/protoc person.proto --cpp_out=./
需要确认protoc执行文件在我的.proto文件的工作目录的./protobuf-2.4.1/src目录下,指定生成cpp文件。


3、在C++中使用Protocol buffer

这个直接上代码吧

#include "person.pb.h"#include <fstream>#include <iostream>using namespace std; /*  class Car;    class Person;    class Person_PhoneNumber;  */intwritesample(){    /* out message usage*/    Car smart ;    smart.set_engine("v12");    smart.set_punishment(200);    Person person ;    person.set_name("jerry");    person.set_id(042);    person.set_email("xxx@126.com");    /* repeated field usage */    Person_PhoneNumber * phonenum = person.add_phone();    phonenum->set_type(Person_PhoneType_MOBILE);    phonenum->set_number("1xx6056xxxx");    /* Write the new address book back to disk. */    fstream output("./log", ios::out | ios::trunc | ios::binary);             if (!person.SerializeToOstream(&output)) {         cerr << "failed to serialize msg." << endl;         return -1;     }    return 0; }intreadsample(){    Person personparser ;    fstream input("./log", ios::in | ios::binary);     if (!personparser.ParseFromIstream(&input)) {         cerr << "failed to parse from stream." << endl;         return -1;     }     cout << personparser.owncar().engine()            << "\n" << personparser.name()            << "\n" << endl;       return 0; }int main(int argc, char* argv[]){    /* sample for serialize to stream */    writesample();    readsample();}

4、编译

定义的makefile如下
Objs = person.pb.o\       main.o\LibGoogleBuf=-L ./lib_proto/ -lprotobuf -lrtall:$(Objs)g++ $(Objs) $(LibGoogleBuf)person.pb.o:person.pb.ccg++ -c person.pb.ccmain.o:main.cppg++ -c main.cpp

执行make,如果有link error,请检查protocol buffer的链接库是否正常配置。

5、关于repeated类型

repeated类型是某一类型的数组,访问其元素可以通过类似下标的方式访问。
最佳用法请参考各自生成的.h文件的函数。
0 0
原创粉丝点击