关于C#结构与字节数组互相转换

来源:互联网 发布:知乎怎么设置匿名回答 编辑:程序博客网 时间:2024/05/21 11:48
近日工作中用到了C#结构与字节数组的互相转换,经过一番研究,终于成功了。现总结一下,为了简洁起见,我写了一个简单的Console程序来展示思路:
 
(1) 在VS2005 Team Suite环境中创建一个C#控制台项目Test
 
(2) 鼠标在Solution Explorer右击References添加对如下.NET库的引用
  1. Microsoft.Protocols.TestTools
  2. Microsoft.Protocols.TestTools.Messages
如果您的.NET库没有上面两个,那么你需要先安装微软的VSTS插件Spec Explorer。
 
(3)  在Program.cs中头部加入命令空间声明:
  1. using System.IO;
  2. using Microsoft.Protocols.TestTools;
  3. using Microsoft.Protocols.TestTools.Messages;
  4. using Microsoft.Protocols.TestTools.Messages.Marshaling;
(4) 编辑代码使之看起来如下:
  1. namespace Test
  2. {
  3.     class Program
  4.     {
  5.         public struct DEMO_STRUCT
  6.         {
  7.             public uint datalen;
  8.             [Size("datalen")]
  9.             public byte[] data;
  10.         }
  11.         public static byte[] ConvertStructureToByteArray<T>(T objStructure)
  12.         {
  13.             MemoryStream ms = new MemoryStream();
  14.             Channel channel = new Channel(null, ms);
  15.             channel.Write<T>(objStructure);
  16.             byte[] result = ms.ToArray();
  17.             ms.Close();
  18.             return result;
  19.         }
  20.         public static void ConvertByteArrayToStructure<T>(out T objStructure, byte[] byteArray)
  21.         {
  22.             MemoryStream ms = new MemoryStream();
  23.             Channel channel = new Channel(null, ms);
  24.             channel.WriteBytes(byteArray);
  25.             objStructure = channel.Read<T>();
  26.             ms.Close();
  27.         }
  28.         static void Main(string[] args)
  29.         {
  30.             DEMO_STRUCT demoStruct = new DEMO_STRUCT();
  31.             demoStruct.datalen = 1024;
  32.             demoStruct.data = new byte[demoStruct.datalen];
  33.             byte[] demoStructArray = ConvertStructureToByteArray(demoStruct);
  34.             Console.WriteLine(Convert.ToBase64String(demoStructArray));
  35.             DEMO_STRUCT demoStructGet = new DEMO_STRUCT();
  36.             ConvertByteArrayToStructure(out demoStructGet, demoStructArray);
  37.             Console.WriteLine(demoStructGet.datalen);
  38.             Console.ReadLine();
  39.         }
  40.      }
  41. }
(5) 编译成功,运行出来的黑窗口显示了一串Base64字符串,在最后显示1024。这证明我们成功了。
by Loomman, QQ:28077188, MSN: Loomman@hotmail.com QQ裙:30515563 ☆程序天堂☆ 请尊重作者原创,转载注明来自裂帛一剑博客,谢谢合作。