Google protocol buffer程序书写小结

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. }  
  1. message   
  2. Person  
  3. {  
  4.        required int32 id = 1;  
  5.        required string name = 2;  
  6.        optional string email = 3;  
  7. }  

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( "eaglewood2005@tom.com"  );   
  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;   

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值