LoginSignup
0
1

More than 3 years have passed since last update.

C#でProtocolBuffersを使って見た!!

Posted at

🌅新年明けましておめでとうございます🌅

業務の中でProtocolBuffersを使用することになり、
"なんなんそれ..."と思い、習うより慣れろということで動かしてみました。
詳しい説明を知りたい方は先人の方々がわかりやすく解説してくださっているものが
ありますのでそちらを参考にしていただきたいと思います。
ちなみに、私はこちらのページを参考にしました。

手順の流れ

  1. Protocを入手
  2. Protoファイル作成
  3. ProtoファイルからC#のクラスを自動生成する
  4. サンプルプログラムを書く

1. Protocを入手

Homebrewを使用して入手

# terminal
$ brew update     # formula を更新
$ brew upgrade    # 更新があるパッケージを再ビルドする
$ brew install protobuf # protobufをインストール
$ brew upgrade protobuf # protobufをアップグレード

$ protoc --version
libprotoc 3.14.0

2. Protoファイル作成

Human.proto
syntax = "proto3";
package MyPackage;

message Human {
  string name = 1;
  uint32 age = 2;
}

3. ProtoファイルからC#のクラスを自動生成する

・Protoファイルが存在する場所まで移動する。

# terminal
protoc --csharp_out=. -I. Human.proto

4. サンプルプログラムを書く

下準備

・NuGetから Google.Protobuf をインストールする。
・先程の自動生成したcsファイルをRiderのProgram.csと同じ階層に置く。

Program.cs
using System;
using Google.Protobuf;
using MyPackage;

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

            byte[] bytes = human.ToByteArray();
            Console.WriteLine(BitConverter.ToString(bytes)); // 

            // デシリアライズ
            var human2 = new Human();
            human2 = Human.Parser.ParseFrom(bytes);

            Console.WriteLine(human2.Age);
        }
    }
}

#実行結果
0A-07-6E-61-6D-65-30-30-31-10-14
20

参考文献

C#でProtocolBuffersを使う方法
Protocol Buffers 導入メモ Mac/Win
XML、JSON、Protocol Buffersを比較してみました

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1