一、使用环境
系统:ubuntu 14.04
Qt版本:5.2.1
protobuf版本:3.8.0
二、在ubuntu上安装protobuf库
- protobuf开源地址:https://github.com/protocolbuffers/protobuf
- 找到想要3.8.8版本,在ubuntu上下载protobuf源码:https://github.com/protocolbuffers/protobuf/tags
- 将protobuf源码压缩包解压到指定目录;
- 打开一个终端,切换当前目录到protobuf解压文件夹下;
- 然后在终端依次执行以下命令:
当检查protoc的版本时输出:
证明protobuf库安装成功了,后面就可以在我们的代码中使用protobuf库。
三、编写proto文件
message.proro定义如下:
syntax = "proto3";
package tutorial;
message Person {
string name = 1;
int32 id = 2;
string email = 3;
string phone = 4;
}
proto文件的语法见其他相关的资料。
四、使用protoc工具生成proto文件对应的操作类
在终端键入如下命令:protoc --cpp_out=. message.proto回车,生成对应的message.pb.h和message.pb.cc类文件。在生成的类中,每个proto文件的字段都有相对应的类成员变量对应,还有对应set/get类成员函数来操作这些成员变量。后面就可以创建这个类对象,来操作(读写)类成员变量了。
五、创建一个Qt工程, 应用protobuf库
先在Qt工程文件.pro中把protobuf库和protobuf的头文件包含进我们创建的工程:
把message.pb.h和message.pb.cc加入Qt工程,然后实现序列化:
#include <message.pb.h>
using namespace tutorial;
int main(int argc, char *argv[]) {
GOOGLE_PROTOBUF_VERIFY_VERSION;
Person person;
person.set_id(9527);
person.set_name("zhouxingxing");
person.set_phone("110");
std::string filename = "person.bin";
std::fstream output(filename, std::ios::out | std::ios::trunc | std::ios::binary);
if (!person.SerializeToOstream(&output)) {
std::cerr << "Failed to write person." << std::endl;
}
google::protobuf::ShutdownProtobufLibrary();
return 0;
}
然后反序列化:
#include <message.pb.h>
using namespace tutorial;
int main(int argc, char *argv[]) {
GOOGLE_PROTOBUF_VERIFY_VERSION;
Person person;
std::string filename = "person.bin";
fstream input(filename, ios::in | ios::binary);
if (!person.ParseFromIstream(&input)) {
cerr << "Failed to parse person." << endl;
return -1;
}
cout << "id:" << person.id() << endl;
cout << "name:" << person.name() << endl;
cout << "phone:" << person.phone() << endl;
google::protobuf::ShutdownProtobufLibrary();
return 0;
}
反序列化的结果为: