2 protobuf proto3语言指南 2.1 导入定义(import) Import 可选项用于包含其它 proto 文件中定义的 message或 enum等。标准格式如 下
info.proto文件内容如下:
1 2 3 4 5 6 7 8 9 syntax = "proto3" ; package infopack; message info { string addr = 1 ; string group = 2 ; }
addressbook.proto文件内容如下,addressbook.proto文件需要导入info.proto文件的内容:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 syntax = "proto3" ; import "info.proto" ; package tutorial; message Person { string name = 1 ; int32 id = 2 ; string email = 3 ; enum PhoneType //枚举消息类型 { MOBILE = 0 ; HOME = 1 ; WORK = 2 ; } message PhoneNumber { string number = 1 ; PhoneType type = 2 ; } repeated PhoneNumber phones = 4 ; infopack.info tmp = 5 ; } message AddressBook { repeated Person people = 1 ; }
编译proto文件
1 protoc -I=./ --cpp_out=./ *.proto
测试程序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 #include "addressbook.pb.h" #include <iostream> #include <fstream> using namespace std ; void set_addressbook () { tutorial::AddressBook obj; tutorial::Person *p1 = obj.add_people(); p1->set_name("mike" ); p1->set_id(1 ); p1->set_email("mike@qq.com" ); tutorial::Person::PhoneNumber *phone1 = p1->add_phones(); phone1->set_number("110" ); phone1->set_type(tutorial::Person::MOBILE); tutorial::Person::PhoneNumber *phone2 = p1->add_phones(); phone2->set_number("120" ); phone2->set_type(tutorial::Person::HOME); infopack::info *p_info = p1->mutable_tmp(); p_info->set_addr("China" ); p_info->set_group("A" ); fstream output ("pb.xxx" , ios::out | ios::trunc | ios::binary) ; bool flag = obj.SerializeToOstream(&output); if (!flag) { cerr << "Failed to write file." << endl ; return ; } output.close(); } void get_addressbook () { tutorial::AddressBook obj; fstream input ("./pb.xxx" , ios::in | ios::binary) ; obj.ParseFromIstream(&input); input.close(); for (int i = 0 ; i < obj.people_size(); i++) { const tutorial::Person& person = obj.people(i); cout << "第" << i + 1 << "个信息\n" ; cout << "name = " << person.name() << endl ; cout << "id = " << person.id() << endl ; cout << "email = " << person.email() << endl ; for (int j = 0 ; j < person.phones_size(); j++) { const tutorial::Person::PhoneNumber& phone_number = person.phones(j); switch (phone_number.type()) { case tutorial::Person::MOBILE: cout << " Mobile phone #: " ; break ; case tutorial::Person::HOME: cout << " Home phone #: " ; break ; case tutorial::Person::WORK: cout << " Work phone #: " ; break ; } cout << phone_number.number() << endl ; } infopack::info info = person.tmp(); cout << "addr = " << info.addr() << endl ; cout << "group = " << info.group() << endl ; cout << endl ; } } int main () { GOOGLE_PROTOBUF_VERIFY_VERSION; set_addressbook(); get_addressbook(); google::protobuf::ShutdownProtobufLibrary(); return 0 ; }