首先、 使用 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 ;
- }
- 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( "eaglewood2005@tom.com" );
- 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;
- }