Google protocol buffer程序書寫小結

首先、使用protocol buffer語言格式定義文件結構,並用文本編輯器編輯,保存擴展名爲.proto格式的文件。格式參照:http://code.google.com/intl/zh-CN/apis/protocolbuffers/docs/proto.html

其次、對定義好的文件使用protoc進行編譯,生成對應的.cc.h文件。將這兩個文件拷貝到自己的工程目錄,並手動添加到項目中去。

編譯參數:protoc –I=$SRC_DIR –cpp_out=$DES_DIR $SRC_DIR/PROTOFILE.proto

再次、在自己的項目中,手動添加要引入的庫:libprotobuf.lib libproto.lib.

最後、將引入的文件include到自己的項目中,以下包含兩個小步驟:

1、              輸入:定義類,使用 實例名.set_變量() 方法設置文件中的參數—>定義輸出流,使用SerializeToOstream()方法將設置完畢的實例輸出到文件中去—>關閉打開的文件。

2、              輸出:定義類和輸入流—>打開輸入時創建的文件—>使用方法ParseFromIstream()進行文件解析—>使用 實例名.變量() 取得存入數據,或者通過 實例名.has_變量() 判斷是否不爲空,也可以通過 實例名.clear_變量() 進行清除操作。

附錄:

1、  test.proto文件

 

  1. message Person  
  2.   
  3. {  
  4.   
  5.        required int32 id = 1;  
  6.   
  7.        required string name = 2;  
  8.   
  9.        optional string email = 3;  
  10.   
  11. }  

 

2、  測試cpp文件

  1. // prototest.cpp : Defines the entry point for the console application.  
  2. // create by 陳相禮 2009-7-22  
  3.   
  4. #include "stdafx.h"  
  5. #include "test.pb.h"  
  6. #include <iostream>  
  7. #include <fstream>  
  8. // 調試宏  
  9. #define __WRITE_TO_FILE__   0  
  10. using namespace std;  
  11.   
  12.   
  13. int _tmain(int argc, _TCHAR* argv[])  
  14. {  
  15.     Person person;  
  16. #if __WRITE_TO_FILE__   
  17. // 以下爲創建文件  
  18.     person.set_id(123);  
  19.     person.set_name( "cxl" );  
  20.     person.set_email( "[email protected]" );  
  21.   
  22.     fstream out( "person.db", ios::out | ios::binary | ios::trunc );  
  23.     person.SerializeToOstream( &out );  
  24.     out.close();  
  25.   
  26. #else  
  27. // 以下爲讀取文件  
  28.     fstream in( "person.db", ios::in | ios::binary );  
  29.   
  30.     if ( !person.ParseFromIstream( &in ) )  
  31.     {  
  32.         cerr << "解析數據文件person.db失敗!" << endl;  
  33.         exit( 1 );  
  34.     }  
  35.   
  36.     cout << "ID: " << person.id() << endl;  
  37.     cout << "Name: " << person.name() << endl;  
  38.     if ( person.has_email() )  
  39.     {  
  40.         cout << "E-mail: " << person.email() << endl;  
  41.     }  
  42.     
  43.     in.close();  
  44.     getchar();  
  45. #endif  
  46.     return 0;  
  47. }  

 

發佈了18 篇原創文章 · 獲贊 10 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章