C#調用Protobuf封裝對象實例


1. 在github(https://github.com/protocolbuffers/protobuf/releases)上下載protoc.exe(protoc-XXXXX)

2. 在新建工程下創建protobuf文件夾

3. 在protobuf文件夾下放入下載的protoc.exe,新建文本文件,修改名稱為run.bat,向文件添加內容:

@echo off

set src_dir=%cd%
for %%s in (*.proto) do (protoc -I=%src_dir% --csharp_out=%src_dir% %src_dir%\%%s)

pause

4. 在protobuf文件夾下創建編輯proto文件

5. 保存proto文件后運行run.bat,生成XXX.cs。工程右鍵--添加--現有項--找到...\protobuf\XXX.cs,添加

6. 在當前工程--引用(右鍵)--管理NuGet程序包(N)...--瀏覽--搜索Google.Protobuf,執行安裝

7.Demo程序:

----------------------------Demo.proto----------------------------

//交互接口協議
syntax = "proto3";

package demopackage;

message rep
{
int32 repnum = 1;
string repmsg = 2;
double repvalue = 3;
}

----------------------------Program.cs----------------------------

using System;
using System.IO;
using System.Collections.Concurrent;
using System.Text;

namespace ProtoBufDemo
{
class Program
{
static void Main(string[] args)
{
Demopackage.rep rep = new Demopackage.rep();
rep.Repnum = 1;
rep.Repmsg = "Hello";
rep.Repvalue = Math.PI;
//中間變量
ConcurrentQueue cqb = new ConcurrentQueue ();
//對象序列化
byte[] bytes = GetBytesFromProtoObject(rep);
//對象反序列化
var recv = GetProtobufObjectFromBytes<Demopackage.rep>(bytes);
Console.WriteLine(string.Format("num:{0},\nmsg:{1},\nvalue:{2}",recv.Repnum,recv.Repmsg,recv.Repvalue));
Console.ReadKey();
}
///


/// 對象序列化
///

/// 需要序列化的對象
/// 序列化后的buffer
private static byte[] GetBytesFromProtoObject(Google.Protobuf.IMessage msg)
{
using (MemoryStream sndms = new MemoryStream())
{
Google.Protobuf.CodedOutputStream cos = new Google.Protobuf.CodedOutputStream(sndms);
cos.WriteMessage(msg);
cos.Flush();
return sndms.ToArray();
}
}
///
/// 對象反序列化
///

/// 序列化的對象類型
/// 序列化的對象buffer
/// 對象
public static T GetProtobufObjectFromBytes (byte[] bytes) where T : Google.Protobuf.IMessage, new()
{
Google.Protobuf.CodedInputStream cis = new Google.Protobuf.CodedInputStream(bytes);
T msg = new T();
cis.ReadMessage(msg);
return msg;
}
}
}

Demo下載


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM