Protocol Buffer で遊んでみた

【Protocol Buffer とは】
Google 社内で使われているデータ変換のソフトウェア + データ形式で、
XML のようなテキスト形式ではなく、バイナリ形式を使用するので、
XML よりも高速なシリアライズができるそうです。


*.proto という形式のファイルでデータの構造を定義して
それをコンパイルすると C++, Java, Python の各言語のコードが生成されます。


【ダウンロードとインストール】
Protocol Buffer のインストールと proto ファイルのコンパイルはこのへんを見てもらうとして


memo - Protocol Buffer のC++チュートリアルをちょっとだけ

Seasons.NET - GoogleさんのProtocol Buffers

XMLはもう不要!? Google製シリアライズツール「Protocol Buffer」



【実際に使ってみた例】

person.proto

package protocol;

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


person.proto をコンパイルして生成された Person クラスはこんな感じ

namespace protocol {

class Person : public ::google::protobuf::Message {
public:
    Person();
    virtual ~Person();

    Person(const Person& from);

    inline Person& operator=(const Person& from);
    inline static const Person& default_instance();

    inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const;
    inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields();

    static const ::google::protobuf::Descriptor* descriptor();

    Person* New() const;
    int GetCachedSize() const;

    const ::google::protobuf::Descriptor* GetDescriptor() const;
    const ::google::protobuf::Message::Reflection* GetReflection() const;
    ::google::protobuf::Message::Reflection* GetReflection();

    inline bool has_name() const;
    inline void clear_name();
    inline const ::std::string& name() const;
    inline void set_name(const ::std::string& value);
    inline void set_name(const char* value);
    inline ::std::string* mutable_name();

    inline bool has_age() const;
    inline void clear_age();
    inline ::google::protobuf::int32 age() const;
    inline void set_age(::google::protobuf::int32 value);
};

} // namespace protocol


Person クラスを使ってファイルを読み書きした例

#include <iostream>
#include <fstream>
#include "person.pb.h"

using namespace std;

void save()
{
    protocol::Person akira;

    akira.set_name("Akira");
    akira.set_age(23);

    ofstream file("./person.txt");
    if (!file)
        return;

    akira.SerializeToOstream(&file);
}


void load()
{
    ifstream file("./person.txt");
    if (!file)
        return;

    protocol::Person akira;
    akira.ParseFromIstream(&file);

    cout << akira.name() << "," << akira.age() << endl; // Akira,23
}


int main()
{
    save();
    load();

    return 0;
}


出力された person.txt はこんな感じ

Akira

わりと簡単に使えます(インストールはめんどいけど)


# Protocol Buffer も文字列が std::string なんですね