随笔-369  评论-37  文章-0  trackbacks-0
下载protobuf-2.5.0(解压到D:\下)
编译,在目录D:\protobuf-2.5.0\vsprojects\Debug之下,生成若干.lib,.exe程序(好乱,中间文件和生成文件都放到一个目录下了,眼都看花了)

另外单独建立新项目test
将protobuf-2.5.0中生成的libprotobuf.lib、libprotoc.lib、protoc.exe复制到新项目Test的工作目录下

在新项目test工作目录下新建文本文件test.proto
编辑文件test.proto内容如下:

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

在控制台中输入命令
protoc -I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/test.proto
(翻译一下:protoc -I=D:\test\test --cpp_out=D:\test\test D:\test\test\person.proto)
生成文件:
person.pb.cc
person.pb.h
将这两个文件加入到新项目test中,编译新项目
o了!




附:新项目中使用protobuf自动生成的c++文件的相关代码

#include "stdafx.h"
#include "person.pb.h"
#include <iostream>
#include <fstream>


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( "abc" );
    person.set_email( "abc@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;
}







posted on 2013-11-22 11:07 小王 阅读(9331) 评论(0)  编辑 收藏 引用 所属分类: 开源项目

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