Google Protocol Buffer

本文介绍了Google的Protocol Buffer(protobuf),一种序列化格式。详细讲述了如何定义.proto文件,使用protoc编译工具生成C++代码,并提供了写操作和读操作的实例,帮助读者理解protobuf的使用方法。

Protocol Buffer是谷歌的一种序列化格式

使用

首先定义.proto文件

syntax ="proto2";
package tutorial;

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

    enum PhoneType{
        MOBILE=0;
        HOME=1;
        WORK=2;
    }

    message PhoneNumber{
        required string number = 1;
        optional PhoneType type = 2[default = HOME];
    }

    repeated PhoneNumber phones = 4;
}

message AddressBook{
    repeated Person people = 1;
}

其中required表示必须提供,optional表示可选,repeated表示重复。

编译

protoc -I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/addressbook.proto

使用protoc编译, SRC_DIR表示源代码目录,DST_DIR表示输出目标目录,这里–cpp_out表示输出c++代码。

在当前目录编译:

 protoc --cpp_out=.  addressbook.proto

会生成两个文件addressbook.pb.h,addressbook.pb.cc

生成的代码中每个message会生成一个class,每个字段会有set_, has_, clear_方法,如果字段类型是string,会有一个 mutable_方法,返回string的指针。如果字段为repeated,还会有 _ size ,add_ 方法。

写操作实例

#include <fstream>
#include <iostream>
#include <string>
#include "addressbook.pb.h"

using namespace std;

void PromptForAddress(tutorial::Person* person) {
    cout << "Enter person ID number: ";
    int id;
    cin >> id;
    person->set_id(id);
    cin.ignore(256, '\n');

    cout << "Enter name: ";
    getline(cin, *person->mutable_name());

    cout << "Enter email address (blank for none): ";
    string email;
    getline(cin, email);
    if (!email.empty()) {
        person->set_email(email);
    }

    while (true) {
        cout << "Enter a phone number (or leave blank to finish): ";
        string number;
        getline(cin, number);
        if (number.empty()) {
            break;
        }

        tutorial::Person::PhoneNumber* phone_number = person->add_phones();
        phone_number->set_number(number);

        cout << "Is this a mobile, home, or work phone? ";
        string type;
        getline(cin, type);
        if (type == "mobile") {
            phone_number->set_type(tutorial::Person::MOBILE);
        } else if (type == "home") {
            phone_number->set_type(tutorial::Person::HOME);
        } else {
            cout << "Unknown phone type. Using default." << endl;
        }
    }
}

int main(int argc, char* argv[]) {
    GOOGLE_PROTOBUF_VERIFY_VERSION;

    if (argc != 2) {
        cerr << "Usage: " << argv[0] << " ADDRESS_BOOK_FILE" << endl;
        return -1;
    }

    tutorial::AddressBook address_book;

    {
        fstream input(argv[1], ios::in | ios::binary);
        if (!input) {
            cout << argv[1] << ": File not found. Creating a new file." << endl;
        } else if (!address_book.ParseFromIstream(&input)) {
            cerr << "Failed to parse address book." << endl;
            return -1;
        }
    }

    PromptForAddress(address_book.add_people());

    {
        fstream output(argv[1], ios::out | ios::trunc | ios::binary);
        if (!address_book.SerializeToOstream(&output)) {
            cerr << "Failed to write address book." << endl;
            return -1;
        }
    }

    google::protobuf::ShutdownProtobufLibrary();

    return 0;
}

编译:

g++ -o Write WriteAddressbook.cc addressbook.pb.cc -I/usr/local/include/google/protobuf -L/usr/local/lib  -lprotobuf

读操作实例

#include <fstream>
#include <iostream>
#include <string>
#include "addressbook.pb.h"
using namespace std;

void ListPeople(const tutorial::AddressBook& address_book) {
    for (int i = 0; i < address_book.people_size(); i++) {
        const tutorial::Person& person = address_book.people(i);

        cout << "Person ID: " << person.id() << endl;
        cout << " Name: " << person.name() << endl;
        if (person.has_email()) {
            cout << " E-mail address: " << 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;
        }
    }
}

int main(int argc, char* argv[]) {
    GOOGLE_PROTOBUF_VERIFY_VERSION;

    if (argc != 2) {
        cerr << "Usage: " << argv[0] << " ADDRESS_BOOK_FILE" << endl;
        return -1;
    }

    tutorial::AddressBook address_book;

    {
        fstream input(argv[1], ios::in | ios::binary);
        if (!address_book.ParseFromIstream(&input)) {
            cerr << "Failed to parse address book." << endl;
            return -1;
        }
    }

    ListPeople(address_book);

    google::protobuf::ShutdownProtobufLibrary();

    return 0;
}

编译:

g++ -o Read ReadAddressbook.cc addressbook.pb.cc -I/usr/local/include/google/protobuf -L/usr/local/lib  -lprotobuf

通过这两段代码应该能初步了解protobuf的使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值