首先、使用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
- {
- required int32 id = 1;
- required string name = 2;
- optional string email = 3;
- }
2、 測試cpp文件
- // prototest.cpp : Defines the entry point for the console application.
- // create by 陳相禮 2009-7-22
- #include "stdafx.h"
- #include "test.pb.h"
- #include <iostream>
- #include <fstream>
- // 調試宏
- #define __WRITE_TO_FILE__ 0
- using namespace std;
- int _tmain(int argc, _TCHAR* argv[])
- {
- Person person;
- #if __WRITE_TO_FILE__
- // 以下爲創建文件
- person.set_id(123);
- person.set_name( "cxl" );
- person.set_email( "[email protected]" );
- fstream out( "person.db", ios::out | ios::binary | ios::trunc );
- person.SerializeToOstream( &out );
- out.close();
- #else
- // 以下爲讀取文件
- fstream in( "person.db", ios::in | ios::binary );
- if ( !person.ParseFromIstream( &in ) )
- {
- cerr << "解析數據文件person.db失敗!" << endl;
- exit( 1 );
- }
- cout << "ID: " << person.id() << endl;
- cout << "Name: " << person.name() << endl;
- if ( person.has_email() )
- {
- cout << "E-mail: " << person.email() << endl;
- }
- in.close();
- getchar();
- #endif
- return 0;
- }