Protobuf是一种可以实现内存与外存交换的协议接口。这是由谷歌开发的开源工具,目前研究Caffe源码时用到。
一个软件项目 = 数据结构 + 算法 + 参数,对于数据结构和算法我们都已经有较多研究,但不同开发者对参数管理却各有千秋。有人喜欢TXT格式化的参数文件,有人喜欢BIN简单高效,也有人喜欢图形化界面的直观。不一致的参数管理带来很多问题,例如一个项目组内不同成员必须约定一套统一的参数方案,或者称为通信协议,这样便于模块集成。而Protobuf工具就完美解决了这个问题,关键部分代码自动生成,节省了大量的开发、调试时间。
首先下载protobuf,地址(打不开?……不解释)
这里用Linux版本2.5.0
解压:
tar zxvf protobuf-2.5.0.tar.gz
切到主目录:
cd protobuf-2.5.0
编译:
./configure
make
sudo make install
添加环境变量:
export PKG_CONFIG_PATH=$(pwd)
编译examples:
cd examples/
make cpp
这里我们只编译C++代码。
简单的例子,首先编写最简单的,hello.proto
message test
{
required int32 id = 1;
required string name = 2;
optional string message = 3;
repeated string test_net = 4;
}
“required”是必须有值的,而“optional“则为可选项,”repeated“表示后面单元为相同类型的一组向量。
- protoc --cpp_out=. addressbook.proto
运行后生成了两个文件:hello.pb.cc 和hello.pb.h,代码比较长就不贴了。我们的应用程序可以通过自动生成的接口实现参数的序列化/反序列化,代码如下:
#include <iostream>
#include <fstream>
#include <string>
#include "hello.pb.h"
using namespace std;
int main()
{
test mytest;
mytest.set_id(100);
mytest.set_name("star");
mytest.set_message("hello world!");
cout << mytest.id() << endl;
cout << mytest.name() << endl;
cout << mytest.message() << endl;
mytest.add_test_net("testnet");
mytest.add_test_net("trainnet");
for (int i = 0; i < mytest.test_net_size(); ++i)
{
cout << mytest.test_net(i) << endl;
}
fstream output("./data.txt", ios::out | ios::trunc | ios::binary);
if (!mytest.SerializeToOstream(&output))
{
cerr << "Failed to store data " << endl;
return -1;
}
output.close();
test mytest1;
fstream input("./data.txt", ios::in | ios::binary);
if (!mytest1.ParseFromIstream(&input))
{
cerr << "Failed to parse data " << endl;
return -1;
}
input.close();
cout << mytest1.id() << endl;
cout << mytest1.name() << endl;
cout << mytest1.message() << endl;
return 0;
}
message Person {
required int32 age = 1;
required string name = 2;
}
message Family {
repeated Person person = 1;
}
下面以例子简单说明如何使用:
int main(int argc, char* argv[])
{
GOOGLE_PROTOBUF_VERIFY_VERSION;
Family family;
Person* person;
// 添加一个家庭成员,John
person = family.add_person();
person->set_age(25);
person->set_name("John");
// 添加一个家庭成员,Lucy
person = family.add_person();
person->set_age(23);
person->set_name("Lucy");
// 添加一个家庭成员,Tony
person = family.add_person();
person->set_age(2);
person->set_name("Tony");
// 显示所有家庭成员
int size = family.person_size();
cout << "这个家庭有 " << size << " 个成员,如下:" << endl;
for(int i=0; i<size; i++)
{
Person psn = family.person(i);
cout << i+1 << ". " << psn.name() << ", 年龄 " << psn.age() << endl;
}
getchar();
return 0;
}