woaidongmao

文章均收录自他人博客,但不喜标题前加-[转贴],因其丑陋,见谅!~
随笔 - 1469, 文章 - 0, 评论 - 661, 引用 - 0
数据加载中……

试用google Protocol Buffers( 比xml快20~100倍, 支持序列化数据 )

使用指南可以看这篇文章介绍:
http://www.cppblog.com/liquidx/

下载Protocol Buffers:
http://code.google.com/p/protobuf/downloads/list

vc环境下使用则在解压缩文件中有一个vsprojects文件夹, 使用vs来编译出libprotobuf.liblibprotoc.lib
设置你的扩展头文件包含目录为 "D:\protobuf-2.1.0\src"

按照指南, 首先我们定义一个test.proto文件内容如下:

package Test;

message Person {
        required string name = 1;
        required int32 id = 2;
        optional string email = 3;
}



然后用protoc编译器编译出c++模块, 这里有一个已经编译好的编译器, 你也可以从压缩包中的源代码编译出该编译器.
http://protobuf.googlecode.com/files/protoc-2.1.0-win32.zip

用这个指令编译
protoc -I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/test.proto
然后我们得到了
test.pb.h
test.pb.cc
2
c++文件

现在我们可以在项目中使用它了:

#include <iostream>
#include "test.pb.h"
#include <fstream>

#pragma comment( lib, "libprotobuf.lib" )
#pragma comment( lib, "libprotoc.lib" )

int _tmain(int argc, _TCHAR* argv[])
{
    // Verify that the version of the library that we linked against is
    // compatible with the version of the headers we compiled against.
    GOOGLE_PROTOBUF_VERIFY_VERSION;

    // 设置数据, 并序列化到文件
    Test::Person person;
    person.set_id( 123 );
    person.set_name( "liquidx" );
    person.set_email( "liquidx@163.com" );

    std::fstream out( "person.pb", std::ios::out | std::ios::binary | std::ios::trunc );
    person.SerializeToOstream( &out );
    out.close();

    // 从文件中读取数据, 并且反序列化
    Test::Person person1;
    std::fstream in( "person.pb", std::ios::in | std::ios::binary );
    if ( !person1.ParseFromIstream( &in ) ) {
      std::cerr << "Failed to parse person.pb." << std::endl;
      exit(1);
    }

    std::cout << "ID: " << person1.id() << std::endl;
    std::cout << "name: " << person1.name() << std::endl;
    if ( person1.has_email() ) {
      std::cout << "e-mail: " << person1.email() << std::endl;
    }

    // Optional:  Delete all global objects allocated by libprotobuf.
    google::protobuf::ShutdownProtobufLibrary();

    getchar();
    return 0;
}



输出:
ID : 123
name : liquidx
e-mail :
liquidx@163.com

产生的person.pb内容如下(28字节):
liquidx{liquidx@163.com

试用完毕:
感觉Protocol Buffers挺好用的, 项目的某些xml部分可以使用它来替代,这样在数据读取和操作上比xml更加方便直接, 且效率高效
!
用它也可以在网络处理上得到一些好处!

 

posted on 2009-06-23 21:08 肥仔 阅读(1266) 评论(2)  编辑 收藏 引用 所属分类: 网络编程

评论

# re: 试用google Protocol Buffers( 比xml快20~100倍, 支持序列化数据 )  回复  更多评论   

不错 好东西啊
2009-07-06 10:46 | 凡客诚品

# re: 试用google Protocol Buffers( 比xml快20~100倍, 支持序列化数据 )  回复  更多评论   

我们的网页游戏就用这个协议
2012-10-18 17:28 | aaa

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理