C#protobuf3的序列化和反序列化和protobuf3转换cs文件的小工具

最近工作上需要HoloLens和JAVA的Netty服务器对接,Netty上用的是Protobuf3协议,我以前只研究过Protobuf2的协议,这次我会将Protobuf3如何转换成对应的C#脚本和Protobuf3如何序列化和反序列化的功能告诉大家,话不多说,下面开始上脚本。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Google.Protobuf;
using System.IO;
using System;
public class ProtobufferTool
{
    #endregion
    /// 
    /// 序列化protobuf
    /// 
    /// 
    /// 
    public static byte[] Serialize(IMessage msg)
    {
        using (MemoryStream rawOutput = new MemoryStream())
        {
			msg.WriteTo(rawOutput);
            byte[] result = rawOutput.ToArray();
            return result;
        }
    }
    /// 
    /// 反序列化protobuf
    /// 
    /// 
    /// 
    /// 
    public static T Deserialize(byte[] dataBytes) where T : IMessage, new()
    {
        T msg = new T();
        msg= (T)msg.Descriptor.Parser.ParseFrom(dataBytes);
        return msg;
    }
}

由于之前讲过Socket通信相关的脚本,如果要实现Socket相互发送消息的话就只要将协议更换一下就行了。

Protobuf3的下载地址在https://github.com/protocolbuffers/protobuf/releases大家根据自己的需求下载编译出dll,将dll放置到Unity中即可。如果大家不会编译的话就直接用我的dll好了。我在文章的末尾会将转换工具和dll都放上来。

下面我们来讲protobuf3的转换工具如何使用,打开我放在文章末尾的工具目录是这样子的,你们只要将proto文件放置在proto文C#protobuf3的序列化和反序列化和protobuf3转换cs文件的小工具_第1张图片
件夹下,再运行run.bat就能够在cs文件夹下得到相对应的C#脚本。

C#protobuf3的序列化和反序列化和protobuf3转换cs文件的小工具_第2张图片红框框起来的即是我放上来的protobuf的dll

dll和转换工具地址链接:https://pan.baidu.com/s/1igD5BaqLhU3H_0nHinxANw 提取码:lssw

你可能感兴趣的:(probuf,c#,开发语言)