protocol buffer是google一种数据交换格式,独立于语言与平台。google提供了三种语言的实现:java,c++,python。采用二进制格式存储,相比xml进行数据交换快很多。可以用于分布式应用之间的数据通信以及异构环境下的数据存储。项目源码中附带有tutorial程序,不过看起来还是复杂,下面写一个简单用于存储配置信息的demo。
首先编写proto文件如下(里面定义QQ基本信息数据结构):
package demo;
//
message QQ {
required string nickname = 1;
required int32 qqhao = 2; // Unique ID number for this person.
optional string email = 3;
enum Sex {
FEMALE = 0;
MALE = 1;
}
optional Sex mysex = 4;
message Friends {
required string qqhao = 1;
}
repeated Friends friends = 5;
}
然后编译protoc --cpp_out=./ qq.proto 在同目录下生成qq.pb.cc与qq.pb.h两个文件,然后写一个c++文件实现将信息存入磁盘
// See README.txt for information and build instructions.
#include <iostream>
#include <fstream>
#include <string>
#include "qq.pb.h"
using namespace std;
int main(int argc, char* 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;
demo::QQ myqq;
{
fstream input("qq.info", ios::in | ios::binary);
if (input) {
myqq.ParseFromIstream(&input);
}
}
{
myqq.set_nickname("ciaos");
myqq.set_qqhao(123456);
myqq.set_email("123456@qq.com");
myqq.set_mysex(demo::QQ::MALE);
demo::QQ::Friends *fri = myqq.add_friends();
fri->set_qqhao("friend1");
fri = myqq.add_friends();
fri->set_qqhao("friend2");
}
{
//save info to local disk
fstream output("qq.info", ios::out | ios::trunc | ios::binary);
if (!myqq.SerializeToOstream(&output)) {
cerr << "Failed to write address book." << endl;
return -1;
}
}
// Optional: Delete all global objects allocated by libprotobuf.
google::protobuf::ShutdownProtobufLibrary();
return 0;
}
接着生成python的代码(protoc --python_out=./ qq.proto)
#! /usr/bin/python
import qq_pb2
import sys
# Iterates though all people in the AddressBook and prints info about them.
def ReadInfo(myqq):
print "Nickname:", myqq.nickname
print "QQ:", myqq.qqhao
print "E-mail:", myqq.email
for friend in person.friends:
print "Friends:", friend.qqhao
myqq = qq_pb2.QQ()
f = open("qq.info", "rb")
myqq.ParseFromString(f.read())
f.close()
ReadInfo(myqq)
就可以轻松地从文件中读取信息出来了。