0


【Protobuf】基本使用总结+项目实践

概述

序列化与反序列化

网络传输中使用,可以实现将对象转换为二进制序列,然后将二进制序列转换为对象,这一个交互的过程就是序列化。生成的数据,持久化存储到磁盘上的过程,也需要经过序列化和反序列化才可以实现。

  • 序列化:把对象转换为字节序列的过程,序列化就像把一堆不同形状的物品压缩打包成一个标准的箱子,这样就可以轻松的放入仓库或者运输到其他地方
  • 反序列化:把字节序列解压成原来的对象,恢复成可以正常使用的数据,类似于拆开箱子,取出原来的物品

序列化场景分析

  • 存储数据:将某个对象存储到文件或者数据库的时候,需要将其转化为序列化格式,因为我们是不可以直接将内存中的对象直接存储的,必须将其打包后再进行存储
  • 网络传输:网络只可以传输字节,而无法直接传输数据对象,因此在发送对象之前,必须将对象序列化为字节序列,传输完毕后,接收端再将字节序列反序列成原来的对象。这就好似如果想要向网络发送一组数据,需要将其整理成一个标准的数据包,传输后再进行还原

实现序列化的方法

目前主流方法,Protobuf、XML、JSON ,这些都是将数据进行序列化的一种方式

  • XML:早起常用的标记语言格式,相对于比较笨重,传输效率不高
  • **JSON **:轻量级的文本数据格式,适合网络传输和人类阅读,但是因为其是文本格式,在性能和效率上是比不过二进制的

Protobuf特点

  • 语言、平台无关:支持多种编程语言,以及多个平台
  • 高效:比XML更小、更快、更简单
  • 拓展性与兼容性好:支持更新数据结构,不影响和破坏原有的旧程序

网络不直接传输对象的原因

网络传输的本质是比特和字节,这些才是网络传输中可以识别的“语言”。但是计算机中有些结构并不是简单的比特或者字节,例如对象、数组等。

因此想要通过网络传输这些负责的数据时,必须先转换成网络能够理解的比特和字节,这也就是的需要序列化的根本原因。

Protobuf的使用过程

编写.proto文件

.proto文件是用于定义数据结构的协议文件,在这个文件中的,可以定义消息类型以及每个消息属性,message可以理解为数据结构,也就是要传递的对象。

  1. syntax = "proto3";
  2. message Person {
  3. int32 id = 1;
  4. string name = 2;
  5. string email = 3;
  6. }

编译.proto文件

使用编译器编译.proto文件后,这些源文件包含了对象序列化和反序列化的方法。

例如编译后代码会生成用来处理Person对象的各种方法,例如序列化(转成二进制)和反序列化(二进制还原成对象)的方法。

生成的代码用于业务逻辑

具体业务中,业务代码可以直接编译生成的接口,比如序列化和反序列化的方法,处理从.proto文件定义的消息。所以在具体使用中,只需调用对应的接口即可,不需要自己实现序列化和反序列化的逻辑。

项目实践

1.0 版本

指定使用proto的版本

  1. syntax = "proto3";

package声明符

表明.proto文件的命名空间,也就是在项目中具有唯一性。其作用就是要避免我们定义的消息出现冲突。 该声明符就是为了防止在多人合作场景下,不同人定义了相同的名称消息类型,从而导致命名冲突,所以使用该声明符的目的就是避免该冲突。

  1. syntax = "proto3"; // 指定使用 proto3 语法
  2. package contacts; // 声明 package 名称为 contacts

** 消息的定义格式**

  1. message PeopleInfo {
  2. int32 id = 1;
  3. string name = 2;
  4. string email = 3;
  5. }
  • 定义消息格式是Protobuf实现的关键部分,用于定义数据结构
  • 每个message包含多个字段,字段类型和编号是必须唯一的
  • 通过Protobuf,数据可以被高效序列化并在不同系统中进行传输

** 字段基本格式**

  • 字段类型:例如int32表示的是字段数据类型
  • 字段名称:给该字段起一个别名
  • 字段唯一编号:字段的标识符、必须是正整数而且是唯一的,只要设定了就不可以改变
  1. int32 id = 1;
  2. string name = 2;
  3. 字段类型 字段名称 = 字段唯一编号;

字段类型

  • 标准数据类型:也就是常见的一些数据类型,包括整数、浮点数、布尔值等 - int32,int64:32位或者64位整数- float,double:单精度和双精度浮点数- bool :布尔值
  • 特殊类型- 枚举类型:一般用于定义固定值的集合,适用于状态、类型等字段- 嵌套message类型:可以将message作为另一个message的字段,从而表示复杂的嵌套结构
  1. message Address {
  2. string street = 1;
  3. string city = 2;
  4. }
  5. message Person {
  6. string name = 1;
  7. Address address = 2; // 嵌套的 Address message
  8. }

字段编号

  • 每个字段必须分配一个唯一的正整数编号,字段编号一旦使用就不可以更改,因为Protobuf在序列化和反序列化都是根据这些编号来映射字段的
  • 编号在1--15中间值最优,大于这个值也可以
  1. message Person {
  2. int32 id = 1; // 唯一标识
  3. string name = 2; // 名字
  4. int32 age = 3; // 年龄
  5. bool is_active = 4; // 活跃状态
  6. }

**编译格式 **

  1. protoc [--proto_path=IMPORT_PATH] --cpp_out=DST_DIR path/to/file.proto
  • ** protoc:**指定编译工具
  • --proto_path = IMPORT_PATH:指定.proto文件的导入路径,其中IMPORT_PATH就是需要编译的.proto文件所在的路径(如果不指定参数的话,则会在当前目录中寻找相应文件)
  • --cpp_out=DST_DIR:指定生成C++代码的输出目录
  • path...:需要编译.proto文件的路径,可以是相对路径也可以是绝对路径
  1. //具体事例
  2. protoc --cpp_out=. contacts.proto

** 生成文件分析**

  • .pb.h文件:头文件,其中包含消息类型的声明与Protobuf相关的序列化、反序列化方法
  • .pb.cc文件:源文件,包含消息类型的实现和相关序列化、反序列化代码
  • 生成的文件中包含序列化和反序列化方法

整合测试

  1. // .proto文件
  2. syntax = "proto3";
  3. package example;
  4. message Person {
  5. string name = 1;
  6. int32 id = 2;
  7. string email = 3;
  8. }
  1. // test.cc
  2. #include <iostream>
  3. #include <fstream>
  4. #include "example.pb.h"
  5. using namespace example;
  6. int main() {
  7. // 创建一个 Person 消息实例
  8. Person person;
  9. person.set_name("张三");
  10. person.set_id(1234);
  11. person.set_email("zhangsan@example.com");
  12. // 序列化后的数据以二进制的方式写入到文件
  13. std::ofstream output("person.dat", std::ios::binary);
  14. if (!person.SerializeToOstream(&output)) {
  15. std::cerr << "Failed to write serialized message." << std::endl;
  16. return -1;
  17. }
  18. // 清空输出流
  19. output.close();
  20. // 从文件中反序列化消息
  21. Person restored_person;
  22. std::ifstream input("person.dat", std::ios::binary);
  23. if (!restored_person.ParseFromIstream(&input)) {
  24. std::cerr << "Failed to parse message from file." << std::endl;
  25. return -1;
  26. }
  27. // 输出反序列化后的消息
  28. std::cout << "Restored Person:" << std::endl;
  29. std::cout << "Name: " << restored_person.name() << std::endl;
  30. std::cout << "ID: " << restored_person.id() << std::endl;
  31. std::cout << "Email: " << restored_person.email() << std::endl;
  32. return 0;
  33. }

2.0 版本

重新编译一次.proto文件

此处对文件进行重新编译后,编译生成的文件会直接将contacts.pb.h和contacts.pb.cc文件覆盖掉

  1. syntax = "proto3";
  2. package c_contacts;
  3. message PeopleInfo{
  4. string name =1;
  5. int32 age =2;
  6. message Phone{
  7. string number =1;
  8. }
  9. repeated Phone phone =3;
  10. }
  11. message Contacts{
  12. repeated PeopleInfo contacts =1;
  13. }
  1. // 编译命令
  2. protoc --cpp_out=.contacts.proto

Protobuf常见操作方法

** Protobuf会为每一个字段生成一个API接口**

Protobuf生成的代码为每个字段都提供了常用的操作方法

  • clear_:重置字段
  • set_和getter:设置和获取字段值
  • mutable_:修改嵌套消息对象
  • add_和_size:用于操作repeated字段

清除字段

每个字段都有一个以clear_开头的方法,这个方法会将字段的值重置为空

  1. person.clear_name(); // 将 person 对象的 name 字段重置为空字符串

字段设置和获取方法

set_开头的方法就是用于设置字段数值的,获取某些数值则用小写方式获取

  1. person.set_name("张三");
  2. std::string name = person.name(); // 获取 name 字段的值

获取嵌套消息指针mutable_方法

mutable_方法可以用来获取嵌套消息指针并允许直接修改嵌套的消息对象

  1. PeopleInfo::Phone* phone = person.mutable_phone();
  2. phone->set_number("123-4567");

** 处理repeated字段**

add_方法

通过该方法可以向repeated字段中添加新元素,即每次调用该元素的时候,都会向数组中添加一个新元素

  1. person.add_phone()->set_number("123-4567");

_size方法

用于获取repeated字段的元素个数,用于判断当前数组中包含多少个元素

  1. int phone_count = person.phone_size(); // 获取 phone 字段的元素个数

数据输入与持久化

实现逻辑梳理

  • 检测输入参数,可以通过命令行指定通讯录文件,如果没有正确的文件路径会输出错误信息提
  • 读取或创建通讯录文件,如果文件不存在就会创建一个新文件,如果文件存在则会反序列化已经有的通讯录数据
  • 添加新的联系人,通过AddPeopleInfo函数去获取输入联系人的信息,然后将其添加到contacts中,简单来说就是添加联系人追加到现有的通讯录中
  • 将联系人保存到文件中,文件保存为二进制的形式,下一次程序运行的时候可以重新读取并继续操作

具体实现

设计并编译.proto文件

  1. syntax = "proto3";
  2. package contacts;
  3. message PeopleInfo {
  4. string name = 1;
  5. int32 age = 2;
  6. repeated PhoneInfo phones = 3;
  7. }
  8. message PhoneInfo {
  9. string number = 1;
  10. }
  11. message Contacts {
  12. repeated PeopleInfo contacts = 1;
  13. }

创建write.cc

  1. #include <iostream>
  2. #include <fstream>
  3. #include <string>
  4. #include "contacts.pb.h" // 引入生成的 Protobuf 头文件
  5. using namespace std;
  6. using namespace contacts; // 使用 contacts 命名空间
  7. // 添加联系人信息
  8. void AddPeopleInfo(PeopleInfo* people_info_ptr) {
  9. cout << "请输入联系人姓名: ";
  10. string name;
  11. getline(cin, name);
  12. people_info_ptr->set_name(name);
  13. cout << "请输入联系人年龄: ";
  14. int age;
  15. cin >> age;
  16. cin.ignore(); // 忽略换行符
  17. people_info_ptr->set_age(age);
  18. cout << "请输入电话号码: ";
  19. string number;
  20. while (true) {
  21. cout << "输入号码(按回车键结束): ";
  22. getline(cin, number);
  23. if (number.empty()) {
  24. break;
  25. }
  26. PhoneInfo* phone = people_info_ptr->add_phones();
  27. phone->set_number(number);
  28. }
  29. }
  30. int main(int argc, char* argv[]) {
  31. GOOGLE_PROTOBUF_VERIFY_VERSION;
  32. if (argc != 2) {
  33. cerr << "Usage: " << argv[0] << " CONTACTS_FILE" << endl;
  34. return -1;
  35. }
  36. Contacts contacts;
  37. // 读取现有的通讯录数据
  38. fstream input(argv[1], ios::in | ios::binary);
  39. if (!input) {
  40. cout << argv[1] << ": File not found. Creating a new file." << endl;
  41. } else if (!contacts.ParseFromIstream(&input)) {
  42. cerr << "Failed to parse contacts." << endl;
  43. return -1;
  44. }
  45. // 添加新的联系人
  46. AddPeopleInfo(contacts.add_contacts());
  47. // 将联系人信息序列化到文件中
  48. fstream output(argv[1], ios::out | ios::trunc | ios::binary);
  49. if (!contacts.SerializeToOstream(&output)) {
  50. cerr << "Failed to write contacts." << endl;
  51. return -1;
  52. }
  53. google::protobuf::ShutdownProtobufLibrary();
  54. return 0;
  55. }

Makefile

  1. write: write.cc contacts.pb.cc
  2. g++ -o write write.cc contacts.pb.cc -std=c++11 -lprotobuf
  3. .PHONY: clean
  4. clean:
  5. rm -f write

2.1版本

基于上述版本,在用户信息中添加了输入多个用户电话的选项

更新联系人的Proto

修改write.cc文件,在输入的时候设置可以输入多个用户信息的选项

修改read.cc文件

整合编译

源码归纳

  1. // contact.proto
  2. syntax = "proto3";
  3. package contacts;
  4. // 定义人员信息的message
  5. message PeopleInfo {
  6. string name = 1; // 姓名
  7. int32 age = 2; // 年龄
  8. // 定义电话号码的message
  9. message Phone {
  10. string number = 1; // 电话号码
  11. // 定义枚举类型,表示电话号码类型
  12. enum PhoneType {
  13. MP = 0; // 移动电话
  14. TEL = 1; // 固定电话
  15. }
  16. PhoneType type = 2; // 电话类型字段
  17. }
  18. repeated Phone phone = 3; // 人员信息可以有多个电话
  19. }
  20. // 定义通讯录
  21. message Contacts {
  22. repeated PeopleInfo contacts = 1;
  23. }
  1. // write.cc
  2. #include <iostream>
  3. #include <fstream>
  4. #include "contacts.pb.h"
  5. using namespace std;
  6. using namespace contacts;
  7. // 新增联系人信息
  8. void AddPeopleInfo(PeopleInfo* people_info_ptr) {
  9. cout << "------新增联系人------" << endl;
  10. // 获取联系人姓名
  11. cout << "请输入联系人姓名: ";
  12. string name;
  13. getline(cin, name);
  14. people_info_ptr->set_name(name);
  15. // 获取联系人年龄
  16. cout << "请输入联系人年龄: ";
  17. int age;
  18. cin >> age;
  19. people_info_ptr->set_age(age);
  20. cin.ignore(256, '\n');
  21. // 添加电话信息
  22. for (int i = 1; ; i++) {
  23. cout << "请输入联系人电话(只按回车跳过添加新电话): ";
  24. string number;
  25. getline(cin, number);
  26. if (number.empty()) break;
  27. PeopleInfo::Phone* phone = people_info_ptr->add_phone();
  28. phone->set_number(number);
  29. // 选择电话号码类型
  30. cout << "选择电话号码类型 (1: 移动电话, 2: 固定电话): ";
  31. int type;
  32. cin >> type;
  33. cin.ignore(256, '\n');
  34. switch (type) {
  35. case 1:
  36. phone->set_type(PeopleInfo::Phone::MP); // 设置为移动电话
  37. break;
  38. case 2:
  39. phone->set_type(PeopleInfo::Phone::TEL); // 设置为固定电话
  40. break;
  41. default:
  42. cout << "无效选择,使用默认值" << endl;
  43. }
  44. }
  45. cout << "------添加联系人成功------" << endl;
  46. }
  47. int main(int argc, char* argv[]) {
  48. GOOGLE_PROTOBUF_VERIFY_VERSION;
  49. if (argc != 2) {
  50. cerr << "Usage: " << argv[0] << " OUTPUT_FILE" << endl;
  51. return -1;
  52. }
  53. Contacts contacts;
  54. // 从文件读取已有的联系人信息
  55. fstream input(argv[1], ios::in | ios::binary);
  56. if (!input) {
  57. cout << argv[1] << ": File not found. Creating a new file." << endl;
  58. } else if (!contacts.ParseFromIstream(&input)) {
  59. cerr << "Failed to parse contacts." << endl;
  60. return -1;
  61. }
  62. // 新增联系人
  63. AddPeopleInfo(contacts.add_contacts());
  64. // 将联系人信息写回文件
  65. fstream output(argv[1], ios::out | ios::trunc | ios::binary);
  66. if (!contacts.SerializeToOstream(&output)) {
  67. cerr << "Failed to write contacts." << endl;
  68. return -1;
  69. }
  70. google::protobuf::ShutdownProtobufLibrary();
  71. return 0;
  72. }
  1. // read.cc
  2. #include <iostream>
  3. #include <fstream>
  4. #include "contacts.pb.h"
  5. using namespace std;
  6. using namespace contacts;
  7. // 打印联系人信息
  8. void PrintContacts(const Contacts& contacts) {
  9. for (int i = 0; i < contacts.contacts_size(); i++) {
  10. const PeopleInfo& person = contacts.contacts(i);
  11. cout << "-----联系人 " << i+1 << " -----" << endl;
  12. cout << "姓名: " << person.name() << endl;
  13. cout << "年龄: " << person.age() << endl;
  14. for (int j = 0; j < person.phone_size(); j++) {
  15. const PeopleInfo::Phone& phone = person.phone(j);
  16. cout << "电话 " << j + 1 << ": " << phone.number();
  17. cout << " (" << PeopleInfo::Phone::PhoneType_Name(phone.type()) << ")" << endl;
  18. }
  19. }
  20. }
  21. int main(int argc, char* argv[]) {
  22. GOOGLE_PROTOBUF_VERIFY_VERSION;
  23. if (argc != 2) {
  24. cerr << "Usage: " << argv[0] << " INPUT_FILE" << endl;
  25. return -1;
  26. }
  27. Contacts contacts;
  28. // 从文件中读取联系人信息
  29. fstream input(argv[1], ios::in | ios::binary);
  30. if (!input) {
  31. cerr << argv[1] << ": File not found." << endl;
  32. return -1;
  33. } else if (!contacts.ParseFromIstream(&input)) {
  34. cerr << "Failed to parse contacts." << endl;
  35. return -1;
  36. }
  37. // 打印联系人信息
  38. PrintContacts(contacts);
  39. google::protobuf::ShutdownProtobufLibrary();
  40. return 0;
  41. }

2.2 版本

引入Any类型到通讯录版本中

源码省略,基于2.1代码更改即可

2.3 版本

引入oneof 类型

修改核心代码

完整代码

  1. // write.cc
  2. #include <iostream>
  3. #include <fstream>
  4. #include "contacts.pb.h"
  5. using namespace std;
  6. using namespace contacts;
  7. // 新增联系人信息
  8. void AddPeopleInfo(PeopleInfo* people_info_ptr) {
  9. cout << "------新增联系人------" << endl;
  10. // 获取联系人姓名
  11. cout << "请输入联系人姓名: ";
  12. string name;
  13. getline(cin, name);
  14. people_info_ptr->set_name(name);
  15. // 获取联系人年龄
  16. cout << "请输入联系人年龄: ";
  17. int age;
  18. cin >> age;
  19. people_info_ptr->set_age(age);
  20. cin.ignore(256, '\n');
  21. // 添加电话信息
  22. for (int i = 1; ; i++) {
  23. cout << "请输入联系人电话(只按回车跳过添加新电话): ";
  24. string number;
  25. getline(cin, number);
  26. if (number.empty()) break;
  27. PeopleInfo::Phone* phone = people_info_ptr->add_phone();
  28. phone->set_number(number);
  29. // 选择电话号码类型
  30. cout << "选择电话号码类型 (1: 移动电话, 2: 固定电话): ";
  31. int type;
  32. cin >> type;
  33. cin.ignore(256, '\n');
  34. switch (type) {
  35. case 1:
  36. phone->set_type(PeopleInfo::Phone::MP); // 设置为移动电话
  37. break;
  38. case 2:
  39. phone->set_type(PeopleInfo::Phone::TEL); // 设置为固定电话
  40. break;
  41. default:
  42. cout << "无效选择,使用默认值" << endl;
  43. }
  44. }
  45. //Any补充
  46. Address address;
  47. cout<<"请输入联系人家庭住址:";
  48. string home_address;
  49. getline(cin,home_address);
  50. address.set_home_address(home_address);
  51. cout<<"请输入联系人单位地址:";
  52. string unit_address;
  53. getline(cin,unit_address);
  54. address.set_unit_address(unit_address);
  55. google::protobuf::Any * data = people_info_ptr->mutable_data();
  56. data->PackFrom(address);//address打包到any类型中
  57. //oneof类型添加内容2.3
  58. cout<<"选择将要添加的其他联系方式(1.QQ号 2-微信号):";
  59. int other_contact;
  60. cin>>other_contact;
  61. cin.ignore(256,'\n');
  62. if(other_contact ==1)
  63. {
  64. cout<<"请输入QQ号:";
  65. string qq;
  66. getline(cin,qq);
  67. people_info_ptr->set_qq(qq);
  68. }else if(other_contact ==2){
  69. cout<<"请输入微信号的:";
  70. string weixin;
  71. getline(cin,weixin);
  72. people_info_ptr->set_weixin(weixin);
  73. }else{
  74. cout<<"非法选项!"<<endl;
  75. }
  76. cout << "------添加联系人成功------" << endl;
  77. }
  78. int main(int argc, char* argv[]) {
  79. GOOGLE_PROTOBUF_VERIFY_VERSION;
  80. if (argc != 2) {
  81. cerr << "Usage: " << argv[0] << " OUTPUT_FILE" << endl;
  82. return -1;
  83. }
  84. Contacts contacts;
  85. // 从文件读取已有的联系人信息
  86. fstream input(argv[1], ios::in | ios::binary);
  87. if (!input) {
  88. cout << argv[1] << ": File not found. Creating a new file." << endl;
  89. } else if (!contacts.ParseFromIstream(&input)) {
  90. cerr << "Failed to parse contacts." << endl;
  91. return -1;
  92. }
  93. // 新增联系人
  94. AddPeopleInfo(contacts.add_contacts());
  95. // 将联系人信息写回文件
  96. fstream output(argv[1], ios::out | ios::trunc | ios::binary);
  97. if (!contacts.SerializeToOstream(&output)) {
  98. cerr << "Failed to write contacts." << endl;
  99. return -1;
  100. }
  101. google::protobuf::ShutdownProtobufLibrary();
  102. return 0;
  103. }
  1. // read.cc
  2. #include <iostream>
  3. #include <fstream>
  4. #include "contacts.pb.h"
  5. using namespace std;
  6. using namespace contacts;
  7. // 打印联系人信息
  8. void PrintContacts(const Contacts& contacts) {
  9. for (int i = 0; i < contacts.contacts_size(); ++i) {
  10. const PeopleInfo& person = contacts.contacts(i);
  11. // 打印基本信息
  12. cout << "姓名: " << person.name() << endl;
  13. cout << "年龄: " << person.age() << endl;
  14. // 打印电话信息
  15. for (int j = 0; j < person.phone_size(); ++j) {
  16. const PeopleInfo::Phone& phone = person.phone(j);
  17. cout << "电话 " << j + 1 << ": " << phone.number();
  18. cout << " (" << PeopleInfo::Phone::PhoneType_Name(phone.type()) << ")" << endl;
  19. }
  20. // 检查是否有 Address 信息,并解封 Address
  21. if (person.has_data() && person.data().Is<Address>()) {
  22. Address address;
  23. person.data().UnpackTo(&address);
  24. if(!address.home_address().empty())
  25. {
  26. cout<<"家庭地址:"<<address.home_address()<<endl;
  27. }
  28. if(!address.unit_address().empty())
  29. {
  30. cout<<"单位地址:"<< (address.unit_address()) <<endl;
  31. }
  32. }
  33. //oneof类型数据打印
  34. switch (person.other_contact_case()) {
  35. case PeopleInfo::OtherContactCase::kQq: // 如果设置了 QQ 号
  36. cout << "qq号: " << person.qq() << endl;
  37. break;
  38. case PeopleInfo::OtherContactCase::kWeixin: // 如果设置了微信号
  39. cout << "微信号: " << person.weixin() << endl;
  40. break;
  41. case PeopleInfo::OtherContactCase::OTHER_CONTACT_NOT_SET: // 未设置
  42. cout << "没有设置其他联系信息。" << endl;
  43. break;
  44. }
  45. cout << "--------------------------------------" << endl;
  46. }
  47. }
  48. int main(int argc, char* argv[]) {
  49. GOOGLE_PROTOBUF_VERIFY_VERSION;
  50. if (argc != 2) {
  51. cerr << "Usage: " << argv[0] << " INPUT_FILE" << endl;
  52. return -1;
  53. }
  54. Contacts contacts;
  55. // 从文件中读取联系人信息
  56. fstream input(argv[1], ios::in | ios::binary);
  57. if (!input) {
  58. cerr << argv[1] << ": File not found." << endl;
  59. return -1;
  60. } else if (!contacts.ParseFromIstream(&input)) {
  61. cerr << "Failed to parse contacts." << endl;
  62. return -1;
  63. }
  64. // 打印联系人信息
  65. PrintContacts(contacts);
  66. google::protobuf::ShutdownProtobufLibrary();
  67. return 0;
  68. }
  1. // contacts.proto
  2. syntax = "proto3";
  3. package contacts;
  4. import"google/protobuf/any.proto";
  5. //地址
  6. message Address{
  7. string home_address = 1;
  8. string unit_address = 2;
  9. }
  10. // 定义人员信息的message
  11. message PeopleInfo {
  12. string name = 1; // 姓名
  13. int32 age = 2; // 年龄
  14. // 定义电话号码的message
  15. message Phone {
  16. string number = 1; // 电话号码
  17. // 定义枚举类型,表示电话号码类型
  18. enum PhoneType {
  19. MP = 0; // 移动电话
  20. TEL = 1; // 固定电话
  21. }
  22. PhoneType type = 2; // 电话类型字段
  23. }
  24. repeated Phone phone = 3; // 人员信息可以有多个电话
  25. google.protobuf.Any data = 4;// Any类型数据
  26. oneof other_contact
  27. {
  28. string qq = 5;
  29. string weixin = 6;
  30. }
  31. }
  32. // 定义通讯录
  33. message Contacts {
  34. repeated PeopleInfo contacts = 1;
  35. }

2.4版本

使用map类型表示新增的联系人信息

3.0版本

未知字段+网络版本+option选项

Client代码

  1. // client.cc
  2. #include <iostream>
  3. #include <fstream>
  4. #include<google/protobuf/unknown_field_set.h>
  5. #include "contacts.pb.h"
  6. using namespace std;
  7. using namespace c_contacts;
  8. using namespace google::protobuf;
  9. void PrintfContacts(const Contacts &contacts)
  10. {
  11. for (int i = 0; i < contacts.contacts_size(); ++i)
  12. {
  13. const PeopleInfo &people = contacts.contacts(i);
  14. cout << "------------联系⼈" << i + 1 << "------------" << endl;
  15. cout << "姓名:" << people.name() << endl;
  16. cout << "年龄:" << people.age() << endl;
  17. int j = 1;
  18. for (const PeopleInfo_Phone &phone : people.phone())
  19. {
  20. cout << "电话" << j++ << ": " << phone.number() << endl;
  21. }
  22. //打印未知字段
  23. // const Reflection*reflection = PeopleInfo::GetReflection();
  24. // const UnknownFieldSet& set= reflection->GetUnknownFields(people);
  25. // for(int j =0;j<set.field_count();++j){
  26. // const UnknownField&unknown_field = set.field(j);
  27. // cout<<
  28. // }
  29. }
  30. }
  31. int main(int argc, char*argv[])
  32. {
  33. GOOGLE_PROTOBUF_VERIFY_VERSION;
  34. if(argc!=2)
  35. {
  36. cerr<<"Usage : "<<argv[0]<<"CONTACTS_FILE"<<endl;
  37. return -1;
  38. }
  39. Contacts contacts;
  40. fstream input(argv[1],ios::in | ios::binary);
  41. if(!contacts.ParseFromIstream(&input)){
  42. cerr<<"Failed to parse contacts."<<endl;
  43. input.close();
  44. return -1;
  45. }
  46. PrintfContacts(contacts);
  47. input.close();
  48. google::protobuf::ShutdownProtobufLibrary();
  49. return 0;
  50. }
  1. //contacts.proto
  2. syntax = "proto3";
  3. package c_contacts;
  4. message PeopleInfo{
  5. string name =1;
  6. int32 age =2;
  7. message Phone{
  8. string number =1;
  9. }
  10. repeated Phone phone =3;
  11. }
  12. message Contacts{
  13. repeated PeopleInfo contacts =1;
  14. }
  1. // makefile (Server相似略)
  2. client:client.cc contacts.pb.cc
  3. g++ -o $@ $^ -std=c++11 -lprotobuf
  4. .PHONY:clean
  5. clean:
  6. rm -f client

Server代码

  1. // contacts.proto
  2. syntax = "proto3";
  3. package s_contacts;
  4. message PeopleInfo{
  5. reserved 2;
  6. string name =1;
  7. int32 birthday = 4;
  8. message Phone{
  9. string number =1;
  10. }
  11. repeated Phone phone =3;
  12. }
  13. message Contacts{
  14. repeated PeopleInfo contacts =1;
  15. }
  1. //server.cc
  2. #include <iostream>
  3. #include <fstream>
  4. #include "contacts.pb.h"
  5. using namespace std;
  6. using namespace s_contacts;
  7. void AddPeopleInfo(PeopleInfo *people_info_ptr)
  8. {
  9. cout << "-------------新增联系⼈-------------" << endl;
  10. cout << "请输⼊联系⼈姓名: ";
  11. string name;
  12. getline(cin, name);
  13. people_info_ptr->set_name(name);
  14. // cout << "请输⼊联系⼈年龄: ";
  15. // int age;
  16. // cin >> age;
  17. // people_info_ptr->set_age(age);
  18. // cin.ignore(256, '\n');
  19. cout<<"请输入联系人生日: ";
  20. int birthday;
  21. cin>>birthday;
  22. people_info_ptr->set_birthday(birthday);
  23. cin.ignore(256,'\n');
  24. for (int i = 1;; i++)
  25. {
  26. cout << "请输⼊联系⼈电话" << i << "(只输⼊回⻋完成电话新增): ";
  27. string number;
  28. getline(cin, number);
  29. if (number.empty())
  30. {
  31. break;
  32. }
  33. PeopleInfo_Phone *phone = people_info_ptr->add_phone();
  34. phone->set_number(number);
  35. }
  36. cout << "-----------添加联系⼈成功-----------" << endl;
  37. }
  38. int main(int argc,char*argv[])
  39. {
  40. GOOGLE_PROTOBUF_VERIFY_VERSION;
  41. if(argc!=2)
  42. {
  43. cerr<<"Usage : "<<argv[0]<<"CONTACTS_FILE"<<endl;
  44. return -1;
  45. }
  46. Contacts contacts;
  47. // 先读取已存在的 contacts
  48. fstream input(argv[1], ios::in | ios::binary);
  49. if (!input)
  50. {
  51. cout << argv[1] << ": File not found. Creating a new file." << endl;
  52. }
  53. else if (!contacts.ParseFromIstream(&input))
  54. {
  55. cerr << "Failed to parse contacts." << endl;
  56. input.close();
  57. return -1;
  58. }
  59. // 新增⼀个联系⼈
  60. AddPeopleInfo(contacts.add_contacts());
  61. // 向磁盘⽂件写⼊新的 contacts
  62. fstream output(argv[1], ios::out | ios::trunc | ios::binary);
  63. if (!contacts.SerializeToOstream(&output))
  64. {
  65. cerr << "Failed to write contacts." << endl;
  66. input.close();
  67. output.close();
  68. return -1;
  69. }
  70. input.close();
  71. output.close();
  72. google::protobuf::ShutdownProtobufLibrary();
  73. return 0;
  74. }

proto 3 语法

字段规则修饰符

singular(默认)

singular用于表示字段在消息中出现0次或者1次。也就是说该字段要么不存在,要么只出现一次。proto3中,singular是默认规则,因此字段声明的时候不需要显式添加修饰符。

  1. message Person {
  2. string name = 1; // 默认是 singular,最多出现一次
  3. int32 age = 2; // 默认是 singular,最多出现一次
  4. }

repeated

repeated表示该字段在消息中可以出现0次或者多次,可以简单理解成为数组,也就是说该字段可以保存多个数值。

下面的事例表示一个联系人可以有多个电话号码

  1. message Person {
  2. repeated string phone_numbers = 3; // 一个联系人可以有多个电话号码
  3. }

Protobuf调用规则总结

完整事例理解

  1. #include "contacts.pb.h"
  2. #include <iostream>
  3. #include <fstream>
  4. using namespace std;
  5. using namespace contacts;
  6. int main() {
  7. // 创建 PeopleInfo 实例
  8. PeopleInfo person;
  9. // 使用 set_ 方法设置 name 和 age
  10. person.set_name("Alice");
  11. person.set_age(30);
  12. // 获取并打印 name 和 age
  13. cout << "姓名: " << person.name() << endl;
  14. cout << "年龄: " << person.age() << endl;
  15. return 0;
  16. }

Message的调用

set_和get_方法

  1. message PeopleInfo {
  2. string name = 1;
  3. int32 age = 2;
  4. }
  • set_方法:主要就是用于给某个字段赋值
  • get_方法:获取某个字段的数值
  1. // 设置字段的值
  2. PeopleInfo person;
  3. person.set_name("Alice");
  4. person.set_age(25);
  5. // 获取字段的值
  6. std::string name = person.name();
  7. int age = person.age();

基于完整事例的设置和获取

  1. #include "contacts.pb.h"
  2. #include <iostream>
  3. #include <fstream>
  4. using namespace std;
  5. using namespace contacts;
  6. int main() {
  7. // 创建 PeopleInfo 实例
  8. PeopleInfo person;
  9. // 使用 set_ 方法设置 name 和 age
  10. person.set_name("Alice");
  11. person.set_age(30);
  12. // 获取并打印 name 和 age
  13. cout << "姓名: " << person.name() << endl;
  14. cout << "年龄: " << person.age() << endl;
  15. return 0;
  16. }

repeated字段调用

类似于数组或者列表,Protobuf会给该字段生成方法来增加、获取以及遍历

  1. message PeopleInfo {
  2. repeated Phone phone = 3;
  3. }

添加元素:注意该处的使用方法,主要就是使用add_方法实现

  1. PeopleInfo person;
  2. PeopleInfo::Phone* phone = person.add_phone();
  3. phone->set_number("123456789");
  4. phone->set_type(PeopleInfo::Phone::MP);

获取元素:使用message.field_size()方法获取repeated字段的长度,然后通过下标访问元素(注意该处的使用方法与其他不同

  1. for (int i = 0; i < person.phone_size(); i++) {
  2. std::string number = person.phone(i).number();
  3. PeopleInfo::Phone::PhoneType type = person.phone(i).type();
  4. }

完整事例代码

  1. int main() {
  2. PeopleInfo person;
  3. person.set_name("Bob");
  4. person.set_age(25);
  5. // 使用 add_ 方法添加多个电话号码
  6. PeopleInfo::Phone* phone1 = person.add_phone();
  7. phone1->set_number("123456789");
  8. phone1->set_type(PeopleInfo::Phone::MP);
  9. PeopleInfo::Phone* phone2 = person.add_phone();
  10. phone2->set_number("987654321");
  11. phone2->set_type(PeopleInfo::Phone::TEL);
  12. // 遍历 phone 字段
  13. for (int i = 0; i < person.phone_size(); i++) {
  14. const PeopleInfo::Phone& phone = person.phone(i);
  15. cout << "电话 " << i + 1 << ": " << phone.number();
  16. cout << " (" << PeopleInfo::Phone::PhoneType_Name(phone.type()) << ")" << endl;
  17. }
  18. return 0;
  19. }

枚举类型的调用

  1. enum PhoneType {
  2. MP = 0; // 移动电话
  3. TEL = 1; // 固定电话
  4. }

通过set_type()方法为phoneType字段赋值

  1. PeopleInfo::Phone phone;
  2. phone.set_type(PeopleInfo::Phone::MP); // 设置电话类型为移动电话

获取枚举资源的类型,也就是Enum_Name()方法

  1. PeopleInfo::Phone::PhoneType type = phone.type();
  2. std::cout << PeopleInfo::Phone::PhoneType_Name(type) << std::endl; // 输出"MP"

完整代码事例

  1. int main() {
  2. PeopleInfo person;
  3. person.set_name("Charlie");
  4. person.set_age(40);
  5. // 添加电话号码并设置枚举类型
  6. PeopleInfo::Phone* phone = person.add_phone();
  7. phone->set_number("1357924680");
  8. phone->set_type(PeopleInfo::Phone::MP); // 设置为移动电话
  9. // 输出枚举类型为可读的字符串
  10. cout << "电话号码: " << phone->number() << endl;
  11. cout << "电话类型: " << PeopleInfo::Phone::PhoneType_Name(phone->type()) << endl;
  12. return 0;
  13. }

序列化与反序列化

序列化,将contacts数据写入到文件contacts.bin文件中

  1. fstream output("contacts.bin", ios::out | ios::trunc | ios::binary);
  2. if (!contacts.SerializeToOstream(&output)) {
  3. cerr << "Failed to write contacts." << endl;
  4. }

反序列化:从文件contacts.bin中读取并解析数据,然后填充到contacts对象中

  1. fstream input("contacts.bin", ios::in | ios::binary);
  2. if (!contacts.ParseFromIstream(&input)) {
  3. cerr << "Failed to parse contacts." << endl;
  4. }

完整代码事例(结合开头代码理解)

  1. int main() {
  2. // 创建并填充 PeopleInfo 实例
  3. PeopleInfo person;
  4. person.set_name("Dave");
  5. person.set_age(22);
  6. PeopleInfo::Phone* phone = person.add_phone();
  7. phone->set_number("5551234");
  8. phone->set_type(PeopleInfo::Phone::TEL);
  9. // 序列化到文件
  10. fstream output("contacts.bin", ios::out | ios::trunc | ios::binary);
  11. if (!person.SerializeToOstream(&output)) {
  12. cerr << "Failed to write to file." << endl;
  13. return -1;
  14. }
  15. output.close();
  16. // 从文件反序列化
  17. PeopleInfo new_person;
  18. fstream input("contacts.bin", ios::in | ios::binary);
  19. if (!new_person.ParseFromIstream(&input)) {
  20. cerr << "Failed to read from file." << endl;
  21. return -1;
  22. }
  23. input.close();
  24. // 输出反序列化后的内容
  25. cout << "姓名: " << new_person.name() << endl;
  26. cout << "年龄: " << new_person.age() << endl;
  27. for (int i = 0; i < new_person.phone_size(); i++) {
  28. const PeopleInfo::Phone& phone = new_person.phone(i);
  29. cout << "电话 " << i + 1 << ": " << phone.number();
  30. cout << " (" << PeopleInfo::Phone::PhoneType_Name(phone.type()) << ")" << endl;
  31. }
  32. return 0;
  33. }

消息类型的定义与使用

嵌套消息类型

一个消息体中嵌套着另一个消息体,通过这种方式将消息组织的更加紧密

  1. syntax = "proto3";
  2. package contacts;
  3. message PeopleInfo {
  4. string name = 1; // 联系人姓名
  5. int32 age = 2; // 联系人年龄
  6. // 嵌套定义 phone_number
  7. message Phone {
  8. string number = 1; // 电话号码
  9. }
  10. }

非嵌套消息类型

  1. syntax = "proto3";
  2. package contacts;
  3. // 独立定义 phone_number
  4. message Phone {
  5. string number = 1; // 电话号码
  6. }
  7. // 独立定义联系人信息
  8. message PeopleInfo {
  9. string name = 1; // 联系人姓名
  10. int32 age = 2; // 联系人年龄
  11. }

跨文件导入消息

**phone.proto文件 **

  1. syntax = "proto3";
  2. package phone;
  3. message Phone {
  4. string number = 1; // 电话号码
  5. }

contacts.proto文件

通过import引入文件,然后通过phone.Phone来调用另一个文件中的消息类型

  1. syntax = "proto3";
  2. package contacts;
  3. import "phone.proto"; // 使用 import 导入 phone.proto 文件
  4. message PeopleInfo {
  5. string name = 1; // 联系人姓名
  6. int32 age = 2; // 联系人年龄
  7. repeated phone.Phone phone = 3; // 使用导入的 Phone 消息
  8. }

repeated类型字段

Protobuf会为repeated字段生成一组函访问器函数

add_contacts()

  • 作用:用于向contacts字段中追加一个新的peopleInfo对象(对应2.0版本)
  • 返回值:返回一个新添加的peopleInfo对象的指针,这样就可以对这个新对象设置各个字段的值
  • 实现机制:每次调用该函数,Protobuf底层会动态调整contacts数组的大小,并返回一个指向新分配的peopleInfo对象的指针
  1. Contacts contacts; // 定义一个 Contacts 对象
  2. // 添加一个新的 PeopleInfo 对象到 contacts 中,并获取该对象的指针
  3. PeopleInfo* new_contact = contacts.add_contacts();
  4. // 设置新联系人信息
  5. new_contact->set_name("John Doe");
  6. new_contact->set_age(30);
  7. // 添加电话号码
  8. PhoneInfo* phone = new_contact->add_phones();
  9. phone->set_number("1234567890");
  10. // 再添加一个电话号码
  11. phone = new_contact->add_phones();
  12. phone->set_number("0987654321");

contacts_size()

  • 作用:返回contacts字段中的元素个数,也就是已经添加的peopleInfo对象的数量
  1. int size = contacts.contacts_size();
  2. std::cout << "Number of contacts: " << size << std::endl;

contacts(int index)

  • 作用:获取contacs中下标index个元素,可以用它来读取或者修改某个特定位置的peopleInfo
  • const版本只可以读,非const版本允许修改
  1. // 获取第一个联系人
  2. const PeopleInfo& first_contact = contacts.contacts(0);
  3. std::cout << "First contact's name: " << first_contact.name() << std::endl;

mutable_contacts(int index)

  • 作用:返回该索引位置对象可变指针,同时允许直接修改该索引位置上的对象
  1. PeopleInfo* mutable_contacts(int index);
  2. PeopleInfo* contact = contacts.mutable_contacts(0);
  3. contact->set_name("Jane Doe");

** clear_contacts()**

  • 作用:清空该字段中的所以元素,然后重置初始状态
  1. contacts.clear_contacts();

mutable_contacts()

  • 作用:返回整个contacts字段的指针,用于进行更加底层的操作
  1. // 原型
  2. ::google::protobuf::RepeatedPtrField< PeopleInfo >* mutable_contacts();
  3. // 使用
  4. auto* contacts_field = contacts.mutable_contacts();
  5. for (int i = 0; i < contacts_field->size(); ++i) {
  6. PeopleInfo* contact = contacts_field->Mutable(i);
  7. // Modify contact...
  8. }

** contacts()**

  • 返回整个contacts字段的不可变引用,可以用于遍历或者读取整个peopleInfo对象,知识返回只读引用,无法修改其内容
  1. const ::google::protobuf::RepeatedPtrField< PeopleInfo >& contacts() const;
  2. const auto& contacts_field = contacts.contacts();
  3. for (int i = 0; i < contacts_field.size(); ++i) {
  4. const PeopleInfo& contact = contacts_field.Get(i);
  5. std::cout << "Contact name: " << contact.name() << std::endl;
  6. }

enum类型

定义和使用的基本规则

  • enum使用大写字母和下划线进行命名
  • 枚举值必须是整数,并且第一个枚举数值必须是0,Protobuf3不做要求,但是Protobuf2做要求
  • 每个枚举值必须是唯一的,只可以是32位有符号整数
  1. enum EnumName {
  2. VALUE_NAME = 0;
  3. ANOTHER_VALUE = 1;
  4. }

enum使用事例

  1. enum PhoneType {
  2. MOBILE = 0;
  3. HOME = 1;
  4. WORK = 2;
  5. }

通讯录2.1版本结合看

枚举类型与message共同使用,整体实现参考通讯录2.1

  1. message Phone {
  2. string number = 1; // 电话号码
  3. PhoneType type = 2; // 电话类型
  4. }

定义中必须遵循的原则

  • 第一个枚举值必须是0
  • 重复枚举值问题,如果同一个Protobuf文件中定义两个相同名称的枚举值(即使他们都属于不同的枚举类型),编译器也同样会报错的。为避免该问题,可以使用不同的package或者明确的命名规则
  • 最大值范围,枚举值必须在32位有符号整数范围内

代码中的具体使用

注意要明确自己传输的是哪一个枚举类型数值,其中**set_type()**是一个setter方法,主要就是用于设置phoneType枚举的值

  1. PeopleInfo person;
  2. Phone* phone = person.add_phones();
  3. phone->set_number("123456789");
  4. phone->set_type(PhoneType::MOBILE); // 设置电话类型为 MOBILE

** 通讯录引入enum后逻辑梳理**

写入联系人逻辑梳理

  • 获取用户输入:程序提示用户输入姓名、年龄以及电话号码
  • 电话号码类型的选择:根据用户选择,将电话类型设置成移动电话或者固定电话
  • 写入数据到文件:将联系人信息保存到文件中,以供后续读取使用

读取联系人的数据逻辑

  • 从文件读取数据:从二进制文件中反序列化出联系人信息
  • 打印联系人信息: 按照联系人枚举类型,将联系人信息打印出来

Any类型

Any的组成

Protobuf中的Any允许存储任意类型的Protobuf消息,这也就解决了动态类型需求,也就是允许一个字段在存储和传输过程中动态变化,而不是一经编译类型就定死了

  1. message Any {
  2. string type_url = 1;
  3. bytes value = 2;
  4. }
  • type_url:字符串类型,保存序列化消息的类型URL
  • value:字节类型,保存序列化的二进制数据

Any类型的使用

使用Any类型的时候,必须将消息序列化为二进制格式后存入Any类型中的value字段中,同时消息类型信息要存储在type_url中

基本流程总结

  • 将消息封装到Any类型中,使用pack方法
  • 从Any类型中解封消息,使用Unpack方法

具体使用理解

定义nay.proto文件并编译

  1. syntax = "proto3"; // 使用 Protobuf 3 语法
  2. package example;
  3. import "google/protobuf/any.proto"; // 导入 Any 类型
  4. // 用户信息
  5. message UserInfo {
  6. string username = 1;
  7. int32 age = 2;
  8. }
  9. // 产品信息
  10. message ProductInfo {
  11. string product_name = 1;
  12. float price = 2;
  13. }
  14. // 通用响应消息,包含 Any 类型
  15. message Response {
  16. google.protobuf.Any data = 1; // Any 类型
  17. }

编写Any字段的主逻辑,封装和解封消息的逻辑

  1. #include<iostream>
  2. #include<fstream>
  3. #include"any.pb.h"
  4. #include"google/protobuf/any.pb.h"
  5. using namespace std;
  6. using namespace example;
  7. using google::protobuf::Any;
  8. int main() {
  9. // Step 1: 创建 Response 对象,用于封装不同的消息类型
  10. Response response;
  11. // Step 2: 创建 UserInfo 消息
  12. UserInfo user;
  13. user.set_username("Alice");
  14. user.set_age(28);
  15. // Step 3: 使用 Any::Pack() 方法将 UserInfo 封装到 Any 中
  16. Any* any_data = response.mutable_data(); // 获取可修改的 Any 字段
  17. any_data->PackFrom(user); // 将 UserInfo 封装到 Any 类型中
  18. // Step 4: 将 Response 序列化到文件中
  19. fstream output("response.bin", ios::out | ios::trunc | ios::binary);
  20. if (!response.SerializeToOstream(&output)) {
  21. cerr << "Failed to write response." << endl;
  22. return -1;
  23. }
  24. output.close();
  25. // Step 5: 从文件反序列化并读取 Response
  26. Response new_response;
  27. fstream input("response.bin", ios::in | ios::binary);
  28. if (!new_response.ParseFromIstream(&input)) {
  29. cerr << "Failed to read response." << endl;
  30. return -1;
  31. }
  32. input.close();
  33. // Step 6: 解封 Any 中的消息,判断是否为 UserInfo 类型
  34. Any any_read = new_response.data();
  35. if (any_read.Is<UserInfo>()) { // 检查 Any 中是否是 UserInfo 类型
  36. UserInfo user_info_read;
  37. if (any_read.UnpackTo(&user_info_read)) { // 解封消息
  38. cout << "UserInfo 解封成功:" << endl;
  39. cout << "用户名: " << user_info_read.username() << endl;
  40. cout << "年龄: " << user_info_read.age() << endl;
  41. }
  42. } else {
  43. cout << "Any 中的消息不是 UserInfo 类型。" << endl;
  44. }
  45. return 0;
  46. }

**代码执行逻辑梳理 **

oneof 类型

基本语法使用

同一个消息中有多个互斥字段,任何时刻只可以有一个字段的数值,也就类似于二选一,该类型必须设计到message类型中。

  1. syntax = "proto3";
  2. package contacts;
  3. // 定义 PeopleInfo 消息
  4. message PeopleInfo {
  5. string name = 1; // 姓名
  6. int32 age = 2; // 年龄
  7. // 定义 oneof 字段,用于表示互斥的联系信息
  8. oneof other_contact {
  9. string qq = 3; // QQ 号
  10. string weixin = 4; // 微信号
  11. }
  12. }

设置与清除数据的方法

设置oneof字段的值

  1. #include <iostream>
  2. #include "contacts.pb.h"
  3. using namespace std;
  4. using namespace contacts;
  5. int main() {
  6. PeopleInfo person; // 创建 PeopleInfo 实例
  7. // 设置基本信息
  8. person.set_name("Alice");
  9. person.set_age(30);
  10. // 设置 oneof 字段的 QQ 号
  11. person.set_qq("12345678");
  12. // 打印信息
  13. cout << "姓名: " << person.name() << endl;
  14. cout << "年龄: " << person.age() << endl;
  15. cout << "qq号: " << person.qq() << endl;
  16. return 0;
  17. }

清除oneof字段的数值

  1. person.clear_qq(); // 清除 QQ 号

设置微信字段

  1. person.set_weixin("alice_wechat"); // 设置微信号,自动清除之前的 QQ 号

** 检查oneof当前的状态**

  • *_case()方法可以用于返回oneof中当前设置的字段
  • other_contact_case()返回一个枚举,表示的是oneof中哪个字段被设置了
  • kQq \ KWeixin是Protobuf自动生成的枚举类型,分别代表的是qq字段和weixin字段被设置
  • OTHER_CONTACT_NOT_SET用于标识oneof中没有任何字段被设置
  1. switch (person.other_contact_case()) {
  2. case PeopleInfo::OtherContactCase::kQq:
  3. cout << "qq号: " << person.qq() << endl;
  4. break;
  5. case PeopleInfo::OtherContactCase::kWeixin:
  6. cout << "微信号: " << person.weixin() << endl;
  7. break;
  8. case PeopleInfo::OtherContactCase::OTHER_CONTACT_NOT_SET:
  9. cout << "未设置联系信息" << endl;
  10. break;
  11. }

**序列化与反序列化的使用 **

  1. // 序列化 PeopleInfo 对象到文件
  2. fstream output("peopleinfo.bin", ios::out | ios::trunc | ios::binary);
  3. if (!person.SerializeToOstream(&output)) {
  4. cerr << "Failed to write person data." << endl;
  5. }
  6. output.close();
  1. // 反序列化 PeopleInfo 对象
  2. fstream input("peopleinfo.bin", ios::in | ios::binary);
  3. PeopleInfo person;
  4. if (!person.ParseFromIstream(&input)) {
  5. cerr << "Failed to parse person data." << endl;
  6. }
  7. input.close();

map 类型

基本语法

  1. map<key_type, value_type> map_field = N;
  1. syntax = "proto3";
  2. package example;
  3. // 定义一个包含 map 的消息
  4. message Person {
  5. string name = 1; // 姓名
  6. int32 id = 2; // 唯一标识符
  7. // 定义一个 map 类型,用于存储联系人名称到电话号码的映射
  8. map<string, string> phone_numbers = 3;
  9. }

map键值支持的类型

  • map的键不可以是浮点类型或者bytes类型,因为Protobuf需要保证键的唯一性以及可排序性
  • map的值可以是标量类型、枚举类型、自定义message类型

具体使用参考(结合上文看)

  1. #include <iostream>
  2. #include "example.pb.h" // 包含生成的 Protobuf 文件
  3. using namespace std;
  4. using namespace example;
  5. int main() {
  6. // 创建 Person 对象
  7. Person person;
  8. person.set_name("Alice");
  9. person.set_id(12345);
  10. // 往 map 中添加联系人信息
  11. PhoneNumber* home_number = (*person.mutable_contacts())["home"];
  12. home_number->set_number("123-456-7890");
  13. home_number->set_type("home");
  14. PhoneNumber* mobile_number = (*person.mutable_contacts())["mobile"];
  15. mobile_number->set_number("098-765-4321");
  16. mobile_number->set_type("mobile");
  17. // 打印联系人信息
  18. for (const auto& contact : person.contacts()) {
  19. cout << "联系类型: " << contact.first << ", 电话号码: " << contact.second.number()
  20. << ", 类型: " << contact.second.type() << endl;
  21. }
  22. return 0;
  23. }

map字段相应操作

插入和访问元素

mutable_contacts()会返回一个指向map<string,phoneNumber>的指针,可以通过类似于数组插入和访问的方式

  1. (*person.mutable_contacts())["home"]; // 获取或创建 key 为 "home" 的值

遍历map的数值

  1. for (const auto& contact : person.contacts()) {
  2. cout << "联系类型: " << contact.first << ", 电话号码: " << contact.second.number() << endl;
  3. }

** 检查元素是否存在**

使用find()方法检查元素是否存在

  1. auto it = person.contacts().find("home");
  2. if (it != person.contacts().end()) {
  3. cout << "找到家庭电话: " << it->second.number() << endl;
  4. } else {
  5. cout << "没有找到家庭电话" << endl;
  6. }

清除map元素

  1. person.mutable_contacts()->clear(); // 清除所有联系人
  2. person.mutable_contacts()->erase("home"); // 删除 key 为 "home" 的联系人信息

默认值

默认值只出现在反序列化中的,只有当Protobuf反序列化一个消息的时候,如果某个字段的二进制数据并不存在,该字段会被设置为默认值。

  • 字符串string:默默认值就是空字符串
  • 字节类型bytes:默认值就是空字节数组
  • 布尔类型bool:默认值是false
  • 数值类型:0
  • 枚举类型:枚举类型定义的第一个枚举值

保留字段

** 保留字段存在的原因**

提前保留一些字段留作他用,主要就是防止未来可能在使用这些字段编号或者引发数据混淆或者兼容性问题,使用保留字段就是为了规避这些问题

  • 当不再需要某些字段,需要删除它们的时候
  • 如果想要避免某个字段编号或者字段名称被重新使用

保留字段使用简单说明

N表示保留字段的名称,name则是要保留字段的名称

  1. reserved N[, N, ...]; // 保留字段编号
  2. reserved "name"[, "name", ...]; // 保留字段名称
  1. message Person {
  2. reserved 3, 4; // 保留字段编号
  3. reserved "age", "address"; // 保留字段名称
  4. int32 id = 1;
  5. string name = 2;
  6. }

只要设置了保留字段和保留编号,如果其他字段使用这些保留的编号或者名称就会导致编译器错误

未知字段

未知字段的理解

旧编译器遇到新编译器定义的字段时,此时就会将这些字段当做未知字段保留,注意旧版本只是对其保留,不会对其处理。

但是在Protobuf3.5以上的版本不仅有保留处理,还可以对其进行子弹处理,也就是说即使反序列化的时候没有识别这些字段,它们仍然会被存储

UnknownFieldSet

主要就是用来存储和操作消息的未知字段

  • GetUnknownFields():用于获取未知字段
  • MutabelUnknownFields():用于获取一个可变的未知字符集,从而可以对这些未知字段进行修改
  • AddVarint(),AddFixed32():可以将不同类型字段数值添加到未知字段中
  1. const google::protobuf::UnknownFieldSet& unknown_fields = message.GetReflection()->GetUnknownFields(message);
  2. for (int i = 0; i < unknown_fields.field_count(); ++i) {
  3. const google::protobuf::UnknownField& field = unknown_fields.field(i);
  4. if (field.type() == google::protobuf::UnknownField::TYPE_VARINT) {
  5. std::cout << "Varint value: " << field.varint() << std::endl;
  6. }
  7. }

反序列化和序列化中的未知字段

如果接收到的消息中包含旧版本中未识别的字段,可以通过以下方式保留并重新序列化

  1. Message message;
  2. message.ParseFromIstream(&input_stream); // 解析包含未知字段的消息
  3. message.SerializeToOstream(&output_stream); // 重新序列化,未知字段仍然会被保留

Reflection接口

Reflection是Protobuf提供的一种动态访问消息字段的方式,其中包含已知字段和未知字段,使用GetReflection接口可以动态访问消息的元数据,并对对消息进行操作

  1. const google::protobuf::Reflection* reflection = message.GetReflection();
  2. const google::protobuf::FieldDescriptor* field = descriptor->field(0);
  3. int value = reflection->GetInt32(message, field);

选项option

Option可以定义多个影.proto文件处理方式的选项,必须改选项可以设置在文件级别、消息级别、字段级别等。这些都会影响Protobuf编译器的行为

选项分类

  • 文件选项(FileOptions):定义文件级别的选项,影响整个 .proto 文件的处理
  • 消息选项(MessageOptions):定义消息类型的选项,影响消息级别的处理
  • 字段选项(FieldOptions):定义字段级别的选项,影响字段的处理
  • 枚举选项(EnumOptions):定义枚举的处理选项
  • 服务选项(ServiceOptions):定义服务类型的处理
  • 方法选项(MethodOptions):定义服务方法的处理

常用选项

optimize_size文件级别选项

作用:Protobuf编译器对代码的优化方式,可以根据下面选项进行优化

  • SPEED:默认选项,如果在性能密集的系统中使用Protobuf使用这个选项,可以让生成的代码高度优化,运行效率高,但是占用空间会大
  • CODE_SIZE:生成占用空间较小的代码,如果想要减少程序的体积使用该选项
  • LITE_RUNTIME:轻量级设备使用,仅仅提供序列化和反序列化功能,省略了完整的反射功能,代码空间占用少

allow_alias(枚举常量选项

作用:允许不同管道枚举值共享共同的整数值,可以给同一个枚举值取多个名字

  1. enum PhoneType {
  2. option allow_alias = true;
  3. MP = 0;
  4. TEL = 1;
  5. LANDLINE = 1; // 若没有 `allow_alias = true`,这里会抛出错误
  6. }

default 字段选项

作用:在Protobuf2中,允许为标量字段设置默认值,如果解码的数据中没有该字段的值,字段就会被设置成默认值

  1. optional int32 id = 1 [default = 100];

**deprecated **

标记一个弃用的字段,也就是表明这些字段不再使用

  1. int32 old_field = 2 [deprecated = true];

**json_name **

为这个字段指定JSON序列化的时候使用的字段名

  1. string user_name = 1 [json_name = "userName"];
标签: c++

本文转载自: https://blog.csdn.net/gma999/article/details/141605410
版权归原作者 gma999 所有, 如有侵权,请联系我们删除。

“【Protobuf】基本使用总结+项目实践”的评论:

还没有评论