Google Protocol Buffer 是一个平台无关、语言无关的结构化数据的序列化与反序列化工具。
wget http://protobuf.googlecode.com/files/protobuf-2.4.1.tar.gz
tar zxvf protobuf-2.4.1.tar.gz
cd protobuf-2.4.1
mkdir /Users/michael/Development/opt/protobuf-2.4.1
./configure --prefix=/Users/michael/Development/opt/protobuf-2.4.1
make
make check
make install
创建一个名为 lm.helloworld.proto 的文件。
package lm;
message helloworld
{
required int32 id = 1; // ID
required string str = 2; // str
optional int32 opt = 3; // optional field
}
一般 Google Protobuf 的 protocol 文件名形如:
packageName.MessageName.proto
此时的目录结构:
protobuf-2.4.1
|---bin
|---include
|---lib
|---test
|---lm.helloworld.proto
编译生成 Google Protobuf 类文件:
alias protoc='/Users/michael/Development/opt/protobuf-2.4.1/bin/protoc'
SRC_DIR=.
DST_DIR=.
protoc -I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/lm.helloworld.proto
此时的目录结构为:
protobuf-2.4.1
|---bin
|---include
|---lib
|---test
|---lm.helloworld.proto
|---lm.helloworld.pb.cc
|---lm.helloworld.pb.h
此处以 File Stream 为例。
#include "lm.helloworld.pb.h"
#include <iostream>
#include <fstream>
using namespace std;
int main(void)
{
lm::helloworld msg1;
msg1.set_id(101);
msg1.set_str("hello");
fstream output("./log", ios::out | ios::trunc | ios::binary);
if (!msg1.SerializeToOstream(&output))
{
cerr << "Failed to write msg." << endl;
return -1;
}
return 0;
}
跟已有的结构化数据结构(依据 Google Protobuf 的格式)创建数据,将结构化数据序列化到流中。
#include "lm.helloworld.pb.h"
#include <iostream>
#include <fstream>
using namespace std;
void ListMsg(const lm::helloworld & msg)
{
cout << msg.id() << endl;
cout << msg.str() << endl;
}
int main(int argc, char* argv[])
{
lm::helloworld msg1;
{
fstream input("./log", ios::in | ios::binary);
if (!msg1.ParseFromIstream(&input))
{
cerr << "Failed to parse address book." << endl;
return -1;
}
}
ListMsg(msg1);
}
将流中的序列化数据,读取到依据 Google Protobuf 的格式创建的对象中。
protobuf-2.4.1
|---bin
|---include
|---lib
|---test
|---lm.helloworld.proto
|---lm.helloworld.pb.cc
|---lm.helloworld.ph.h
|---write.cpp
|---read.cpp
g++ lm.helloworld.pb.cc write.cpp -o write.out -I ../include -L../lib -lprotobuf
Notice:
运行 write:
./write
会观察到生成如下文件(参见源程序):
log
运行 read:
./read
输出结果:
$ ./read.out
101
hello
-
Happy Coding, enjoy sharing!
转载请注明来自“柳大的CSDN博客”:Blog.CSDN.net/Poechant
-