下載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
小王 閱讀(9418)
評論(0) 編輯 收藏 引用 所屬分類:
開源項目