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文件

 


view plaincopy to clipboardprint?
message Person  
  
{  
  
       required int32 id = 1;  
  
       required string name = 2;  
  
       optional string email = 3;  
  
}  
2、  测试cpp文件


view plaincopy to clipboardprint?
// 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;  
}  


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/ttgoo/archive/2010/01/21/5221328.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值