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。工程右键--添加--现有项--找到...protobufXXX.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}, msg:{1}, value:{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下载

原文地址:https://www.cnblogs.com/teyond/p/Csharp_Protobuf.html