Google protocol buffer程式書寫小結

來源:互聯網
上載者:User

首先、使用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檔案

 

message Person</p><p>{</p><p> required int32 id = 1;</p><p> required string name = 2;</p><p> optional string email = 3;</p><p>}<br />

2、  測試cpp檔案

// prototest.cpp : Defines the entry point for the console application.<br />// create by 陳相禮 2009-7-22</p><p>#include "stdafx.h"<br />#include "test.pb.h"<br />#include <iostream><br />#include <fstream><br />// 調試宏<br />#define __WRITE_TO_FILE__ 0<br />using namespace std;</p><p>int _tmain(int argc, _TCHAR* argv[])<br />{<br /> Person person;<br />#if __WRITE_TO_FILE__<br />// 以下為建立檔案<br /> person.set_id(123);<br /> person.set_name( "cxl" );<br /> person.set_email( "eaglewood2005@tom.com" );</p><p> fstream out( "person.db", ios::out | ios::binary | ios::trunc );<br /> person.SerializeToOstream( &out );<br /> out.close();</p><p>#else<br />// 以下為讀取檔案<br /> fstream in( "person.db", ios::in | ios::binary );</p><p> if ( !person.ParseFromIstream( &in ) )<br /> {<br /> cerr << "解析資料檔案person.db失敗!" << endl;<br /> exit( 1 );<br /> }</p><p> cout << "ID: " << person.id() << endl;<br /> cout << "Name: " << person.name() << endl;<br /> if ( person.has_email() )<br /> {<br /> cout << "E-mail: " << person.email() << endl;<br /> }</p><p> in.close();<br /> getchar();<br />#endif<br />return 0;<br />}<br />

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.