ProtoBuf序列化和反序列化方法

最近公司需要将以前的协议全都改成ProtoBuf生成的协议,再将结构体打包和解包过程终于到一些问题 ,无法使用Marshal.SizeOf计算结构体大小,最后找了一下ProtoBuf的文档,可以用它自带的序列化和反序列化方法解决问题。

下面分享一下方法吧。

 1   /// <summary>
 2         ///  将消息序列化为二进制的方法
 3         /// </summary>
 4         /// <param name="meg">要序列化的对象</param>
 5         /// <returns></returns>
 6         public static byte[] Serizlize(object meg)
 7         {
 8             try
 9             {
10                 //涉及格式转换,需要用到流,将二进制序列化到流中
11                 using (MemoryStream ms = new MemoryStream())
12                 {
13                     //使用ProtoBuf工具的序列化方法
14                     ProtoBuf.Serializer.Serialize(ms, meg);
15 
16                     //定义二级制数组,保存序列化后的结果
17                     byte[] result = new byte[ms.Length];
18                     //将流的位置设为0,起始点
19                     //ms.Seek(0, SeekOrigin.Begin);
20                     ms.Position = 0;
21                     //将流中的内容读取到二进制数组中
22                     ms.Read(result, 0, result.Length);
23 
24                     return result;
25                 }
26             }
27             catch (Exception ex)
28             {
29                 return null;
30             }
31         }
32         /// <summary>
33         /// 将收到的消息反序列化成对象
34         /// </summary>
35         /// <param name="msg">收到的消息</param>
36         /// <returns></returns>
37         public static object DeSerizlize<T>(byte[] msg)
38         {
39             try
40             {
41                 using (MemoryStream ms = new MemoryStream())
42                 {
43                     //将消息写入流中
44                     ms.Write(msg, 14, msg.Length-14);
45                     //将流的位置归0
46                     ms.Position = 0;
47                     //使用工具反序列化对象
48                     object mm = ProtoBuf.Serializer.Deserialize<T>(ms);
49                     return mm;
50 
51                 }
52             }
53             catch (Exception ex)
54             {
55                 return null;
56             }
57         }

 

posted @ 2019-01-03 16:36  weirdgiant  阅读(12375)  评论(1编辑  收藏  举报