備忘録

備忘録

C#でProtocolBuffersを使う方法

Ⅰ. はじめに

タイトルの通り「C#でProtocolBuffersを使う方法」です。
本記事ではproto3(ProtocolBuffers version 3)を対象とします。

また、protoファイルを書く時は VisualStudio Codeに vscode-proto3 をインストールして開発する事をおすすめします。

また、ProtocolBuffersをリバースする方法はこちら
https://kagasu.hatenablog.com/entry/2017/03/17/124259

Ⅱ. やり方(Google.Protobufを使う方法)

1. NuGetから Google.Protobuf をインストールする
Install-Package Google.Protobuf
2. protoファイルを作成する

Human.proto

syntax = "proto3";
package MyPackage;

message Human {
  string name = 1;
  uint32 age = 2;
}
3. protoc.exe をダウンロードする

https://github.com/google/protobuf/releases

4. protoファイルからC#のクラスを自動生成する
protoc.exe --csharp_out=../ProtoModel Human.proto
5. サンプルプログラムを書く
using Google.Protobuf;
using MyPackage;

static void Main(string[] args)
{
  var human = new Human
  {
    Name = "name001",
    Age = 20
  };

  byte[] bytes = human.ToByteArray();

  Console.WriteLine(BitConverter.ToString(bytes));

  // デシリアライズ
  // human = Human.Parser.ParseFrom(bytes);
}
実行結果

f:id:kagasu:20180429232357p:plain

Ⅲ. やり方(protobuf-netを使う方法)

1. NuGetから protobuf-net をインストールする
Install-Package protobuf-net
2. protoファイルを作成する

Human.proto

syntax = "proto3";
package MyPackage;

message Human {
  string name = 1;
  uint32 age = 2;
}
3. protogen.exe をダウンロードする

https://github.com/mgravell/protobuf-net/releases

4. protoファイルからC#のクラスを自動生成する
protogen.exe --csharp_out=../ProtoModel Human.proto
5. サンプルプログラムを書く
using ProtoBuf;
using MyPackage;

static void Main(string[] args)
{
  var human = new Human
  {
    Name = "name001",
    Age = 20
  };

  using (var ms = new MemoryStream())
  {
    Serializer.Serialize(ms, human);
    byte[] bytes = ms.ToArray();
    Console.WriteLine(BitConverter.ToString(bytes));

    // デシリアライズ
    // human = Serializer.Deserialize<Human>(ms);
  }
}
実行結果

f:id:kagasu:20180429232357p:plain

Ⅳ. Google.Protobuf (protoc.exe)と protobuf-net (protogen.exe) の違い

1. enumの場合

enum QueryType {
  QUERYTYPE_NONE = 0;
  QUERYTYPE_ALL = 1;
}
Google.Protobuf (protoc.exe)

protoc.exe は C#用に最適化されたC#コードを出力します。
以下のようにC#で書くことができます。

var queryType = QueryType.All;
protobuf-net (protogen.exe)

protogen.exe は愚直に(最適化されていない)C#コードを出力します。
以下のようにC#で書くことができます。

var queryType = QueryType.QuerytypeAll;