protocol buffer使用范例5

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;  */
int
writesample(){

    /* 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; 
}


int
readsample(){
    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 -lrt


all:$(Objs)
	g++ $(Objs) $(LibGoogleBuf)

person.pb.o:person.pb.cc
	g++ -c person.pb.cc

main.o:main.cpp
	g++ -c main.cpp

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

5、关于repeated类型

repeated类型是某一类型的数组,访问其元素可以通过类似下标的方式访问。
最佳用法请参考各自生成的.h文件的函数。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值