很早就听闻过Protocol Buffer是个很神奇的东西,只是没有使用过,由于工作上的需要,决定试试Protocol Buffer,废话不多说,先来看看如何安装Protocol Buffer吧,平台是Linux
安装步骤:
1)下载Protocol Buffer源码包 https://code.google.com/p/protobuf/downloads/list
2) 使用 tar -xvf protobuf-2.5.0.tar.bz2
3) 开始编译protocol buffer
1. ./configure --prefix=/usr/local/protobuf
2. make
3. make check
4. make install
经过了这些步骤之后,就可以开始我们的Protocol Buffer之旅了,下面我们就从最简单的开始吧,一探究竟,在写Protocol Buffer应用之前,我们需要知道使用Protocol Buffer的使用步骤:
1)定义消息结构文件,一般都是以.proto为后缀
2)使用Protocol Buffer 编译器来编译消息结构文件,并且生成对应的***.pb.h 和***.pb.cc文件
3)使用生成的接口文件中的API来实现消息发送与接收
看完了上述步骤之后,我们来写个简单的测试例子,代码如下:
1. 首先定义消息的结构
message Person{
required string name = 1;
required int32 id = 2;
optional string email = 3;
}
message AddressBook{
repeated Person person = 1;
}
在这个结构中,我们定义了两个子结构,其中AddressBook结构包含了一个Person结构,下面我们就使用protoc -I=. --cpp_out=. ./test.proto 来生成test.pb.h和test.pb.cc文件,其中文件test.pb.h文件中生成了很多的接口API,其中我们只需要使用其中的部分API来完成,接下来,我们来看看怎么来使用这些API吧,代码如下:
#include <iostream>
#include <fstream>
#include <string>
#include "test.pb.h"
using namespace std;
void People(const Person& person)
{
cout << "Person ID: " << person.id() << endl;
cout << "Name: " << person.name() << endl;
if (person.has_email()) {
cout << "E-mail address: " << person.email() << endl;
}
}
// Iterates though all people in the AddressBook and prints info about them.
void ListPeople(const AddressBook& address_book) {
for (int i = 0; i < address_book.person_size(); i++) {
const Person& person = address_book.person(i);
People(person);
}
}
void write(const char* filename)
{
Person person;
person.set_id(123);
person.set_name("abc");
person.set_email("abc@126.com");
fstream out(filename,ios::out |ios::binary | ios::trunc);
person.SerializeToOstream(&out);
out.close();
}
// Main function: Reads the entire address book from a file and prints all
// the information inside.
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;
if (argc != 2) {
cerr << "Usage: " << argv[0] <