一、protobuf簡介
protobuf (protocol buffer)是google公司實現的一種數據交換的格式,由於其是一種二進制的格式,相對於xml,json進行數據交換要快很多,且佔用存儲空間更小。因此可以把它用於分佈式應用之間的數據通信的數據交換格式,作爲一種效率和兼容性都非常優秀的二進制數據傳輸格式。
二、protobuf的基礎語法及編譯命令
由於protobuf獨立於平臺語言,Google爲其提供了多種語言的實現,包括Java,C++,Go,Python等,並且爲每一種實現都包含了相應語言的編譯器和庫文件,方便不同語言開發者的使用。
(1)基礎語法
syntax = "proto3";
package testprotobuf;
message Person {
string name = 1; // 字符串類型
int32 age = 2; // int32類型
enum Sex { //枚舉類型
MAN = 0;
WOMAN = 1;
}
Sex sex = 3;
bool flag = 4; // bool類型
}
(2)編譯
使用protoc講proto文件,編譯生成C++的源文件和頭文件,如對test1.proto進行編譯:
protoc test1.proto --cpp_out=./
生成test1.pb.cc和test1.pb.h文件
三、使用proto文件生成的類,對對象進行序列化和反序列化
(1)序列化
#include "test1.pb.h"
#include <iostream>
#include <string>
using namespace std;
using namespace testprotobuf;
int main() {
Person p;
p.set_age(10);
p.set_name("zhangsan");
p.set_sex(testprotobuf::Person::MAN);
p.set_flag(false);
// 序列化
std::string msg;
if (p.SerializeToString(&msg)) {
cout << msg.c_str() << endl;
}
}
g++ main.cc test1.pb.cc -lprotobuf -o main
(2)反序列化
#include "test1.pb.h"
#include <iostream>
#include <string>
using namespace std;
using namespace testprotobuf;
int main() {
Person p;
p.set_age(10);
p.set_name("zhangsan");
p.set_sex(testprotobuf::Person::MAN);
p.set_flag(false);
// 序列化
std::string msg;
if (p.SerializeToString(&msg)) {
cout << msg.c_str() << endl;
}
// 反序列化
Person p1;
if (p1.ParseFromString(msg)) {
cout << p1.name() << endl;
cout << p1.age() << endl;
cout << p1.sex() << endl;
cout << p1.flag() << endl;
}
return 0;
}