一、安裝與環境配置
1、ProtobufC++ 是 Google 開發的一個開源序列化數據格式,支持多語言,對數據進行聲明式的描述,可以生成代碼用於數據的序列化和反序列化。使用 protobuf 前,需要先在本機上安裝 Protocol Buffer,可以在官網下載安裝包,也可以通過源代碼進行安裝。安裝完 protobuf 後,還需要在環境變量中加入 protoc 的路徑。
2、接着,下載 ProtobufC++ 的源碼,使用命令行進入解壓後的目錄,使用 make 進行編譯,生成 libprotobuf.a 和 libprotobuf-lite.a 兩個靜態庫文件,將文件放入 lib 目錄下,再將 include 目錄下的頭文件拷貝到系統目錄中。
示例代碼:
#安裝 protobuf $ sudo apt-get install protobuf-compiler $ sudo apt-get install libprotobuf-dev #下載 ProtobufC++ $ wget https://github.com/protobuf-c/protobuf-c/releases/download/v1.3.3/protobuf-c-1.3.3.tar.gz $ tar -xvf protobuf-c-1.3.3.tar.gz $ cd protobuf-c-1.3.3/ $ ./configure --prefix=/usr $ make $ sudo make install $ sudo ldconfig #檢驗安裝是否成功 $ protoc --version
二、ProtobufC++ 的基本使用
1、定義 proto 文件
定義一個 proto 文件需要遵循一定的格式和規範,定義了消息的名稱、字段個數、類型和順序。下面是一個簡單的 proto 文件:
syntax = "proto3"; message Person { string name = 1; int32 age = 2; bool is_student = 3; }
2、生成 C++ 代碼
使用 protoc 命令將 proto 文件編譯成 C++ 代碼。如下所示:
$ protoc --cpp_out=. person.proto
命令會生成 person.pb.h 和 person.pb.cc 兩個文件。
3、序列化
使用生成的 C++ 代碼對數據進行序列化,將數據打包成二進制格式。下面是一個序列化的示例代碼:
Person person; person.set_name("Tom"); person.set_age(20); person.set_is_student(true); std::string pbStr = person.SerializeAsString();
4、反序列化
使用生成的 C++ 代碼將二進制數據反序列化為原始數據。下面是一個反序列化的示例代碼:
Person person; person.ParseFromString(pbStr); std::cout << person.name() << std::endl; std::cout << person.age() << std::endl; std::cout << person.is_student() << std::endl;
三、ProtobufC++ 的進階用法
1、自定義數據類型
除了支持基本數據類型,ProtobufC++ 還支持自定義數據類型。例如,我們可以定義一個枚舉類型:
enum Gender { UNKNOWN = 0; MALE = 1; FEMALE = 2; } message Person { string name = 1; int32 age = 2; Gender gender = 3; }
2、嵌套類型
可以在 message 中定義其他的 message 或枚舉類型,例如定義一個 Address 類型:
message Address { string province = 1; string city = 2; string area = 3; } message Person { string name = 1; int32 age = 2; Address address = 3; }
3、使用 protobuf 對象作為字段
可以將一個 message 對象作為另一個 message 的字段類型,例如定義一個 Student 類型:
message Course { string name = 1; float score = 2; } message Student { string name = 1; int32 age = 2; repeated Course courses = 3; }
4、使用 oneof 定義多個可選字段
使用 oneof 關鍵字可以定義一個 message 中多個可選字段,只能同時存在一個字段有值。例如定義一個成績類型,可以有學生得分或者課程得分:
message Score { oneof score { float student_score = 1; float course_score = 2; } }
四、ProtobufC++ 常用函數
1、set_字段名()
設置 message 中某個字段的值,函數的名稱為 set_字段名(),例如:
person.set_name("Tom");
2、字段名() 和 mutable_字段名()
獲取 message 中某個字段的值,其中字段名() 用於獲取 const 類型的字段,mutable_字段名() 用於獲取非 const 類型的字段:
std::string name = person.name(); person.mutable_address()->set_city("Shanghai");
3、SerializeToString() 和 ParseFromString()
對 message 進行序列化和反序列化的函數:
std::string pbStr = person.SerializeAsString(); Person person; person.ParseFromString(pbStr);
五、總結
以上就是 ProtobufC++ 的基本使用和進階用法,包括環境配置、 proto 文件定義、生成 C++ 代碼、序列化和反序列化、自定義類型、嵌套類型、使用 message 作為字段、使用 oneof 定義多個可選字段以及常用函數。
通過對 ProtobufC++ 的學習和使用,可以更高效地進行數據序列化和反序列化,使得程序性能更優。
原創文章,作者:RKPGH,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/361565.html