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("[email protected]");

    /* 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文件的函數。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章