protobuf入门笔记

    技术2022-07-10  149

    required: 必须提供该字段的值,否则该消息将被视为“未初始化”。如果是在调试模式下编译 libprotobuf,则序列化一个未初始化的 message 将将导致断言失败。在优化的构建中,将跳过检查并始终写入消息。但是,解析未初始化的消息将始终失败(通过从解析方法返回 false)。除此之外,required 字段的行为与 optional 字段完全相同。

    optional: 可以设置也可以不设置该字段。如果未设置可选字段值,则使用默认值。对于简单类型,你可以指定自己的默认值,就像我们在示例中为电话号码类型所做的那样。否则,使用系统默认值:数字类型为 0,字符串为空字符串,bools 为 false。对于嵌入 message,默认值始终是消息的 “默认实例” 或 “原型”,其中没有设置任何字段。调用访问器以获取尚未显式设置的 optional(或 required)字段的值始终返回该字段的默认值。

    repeated: 该字段可以重复任意次数(包括零次)。相当于std的vector,可以用来存放N个相同类型的内容。

    单值发送

    数据结构

    package tutorial; message Person { required int32 id = 1; required string name = 2; optional string email = 3; }

    main.cpp

    #include <iostream> #include <fstream> #include <string> #include "person.pb.h" using namespace std; int main(int argc, char* argv[]) { GOOGLE_PROTOBUF_VERIFY_VERSION; tutorial::Person person; //将数据写到person.pb文件 person.set_id(123456); person.set_name("Mark"); person.set_email("mark@example.com"); fstream out("person.pb", ios::out | ios::binary | ios::trunc); person.SerializeToOstream(&out); out.close(); //从person.pb文件读取数据 fstream in("person.pb", ios::in | ios::binary); if (!person.ParseFromIstream(&in)) { cerr << "Failed to parse person.pb." << endl; exit(1); } cout << "ID: " << person.id() << endl; cout << "name: " << person.name() << endl; if (person.has_email()) { cout << "e-mail: " << person.email() << endl; } getchar(); return 0; }

    多值发送

    数据结构

    message Person { required int32 age = 1; required string name = 2; } message Family { repeated Person person = 1; }

    main函数

    #include <iostream> #include <fstream> #include <string> #include "person.pb.h" using namespace std; int main(int argc, char* argv[]) { GOOGLE_PROTOBUF_VERIFY_VERSION; Family family; Person* person; // 添加一个家庭成员,John person = family.add_person(); person->set_age(25); person->set_name("John"); // 添加一个家庭成员,Lucy person = family.add_person(); person->set_age(23); person->set_name("Lucy"); // 添加一个家庭成员,Tony person = family.add_person(); person->set_age(2); person->set_name("Tony"); // 显示所有家庭成员 int size = family.person_size(); cout << "这个家庭有 " << size << " 个成员,如下:" << endl; for (int i = 0; i < size; i++) { Person psn = family.person(i); cout << i + 1 << ". " << psn.name() << ", 年龄 " << psn.age() << endl; } getchar(); return 0; } 这个家庭有 3 个成员,如下: 1. John, 年龄 25 2. Lucy, 年龄 23 3. Tony, 年龄 2

    参考链接: https://www.jianshu.com/p/d2bed3614259 https://www.it610.com/article/4829050.htm

    Processed: 0.012, SQL: 9