近日工作中用到了C#结构与字节数组的互相转换,经过一番研究,终于成功了。现总结一下,为了简洁起见,我写了一个简单的Console程序来展示思路:
(1) 在VS2005 Team Suite环境中创建一个C#控制台项目Test
(2) 鼠标在Solution Explorer右击References添加对如下.NET库的引用
- Microsoft.Protocols.TestTools
- Microsoft.Protocols.TestTools.Messages
如果您的.NET库没有上面两个,那么你需要先安装微软的VSTS插件Spec Explorer。
(3) 在Program.cs中头部加入命令空间声明:
- using System.IO;
- using Microsoft.Protocols.TestTools;
- using Microsoft.Protocols.TestTools.Messages;
- using Microsoft.Protocols.TestTools.Messages.Marshaling;
(4) 编辑代码使之看起来如下:
- namespace Test
- {
- class Program
- {
- public struct DEMO_STRUCT
- {
- public uint datalen;
- [Size("datalen")]
- public byte[] data;
- }
- public static byte[] ConvertStructureToByteArray<T>(T objStructure)
- {
- MemoryStream ms = new MemoryStream();
- Channel channel = new Channel(null, ms);
- channel.Write<T>(objStructure);
- byte[] result = ms.ToArray();
- ms.Close();
- return result;
- }
- public static void ConvertByteArrayToStructure<T>(out T objStructure, byte[] byteArray)
- {
- MemoryStream ms = new MemoryStream();
- Channel channel = new Channel(null, ms);
- channel.WriteBytes(byteArray);
- objStructure = channel.Read<T>();
- ms.Close();
- }
- static void Main(string[] args)
- {
- DEMO_STRUCT demoStruct = new DEMO_STRUCT();
- demoStruct.datalen = 1024;
- demoStruct.data = new byte[demoStruct.datalen];
- byte[] demoStructArray = ConvertStructureToByteArray(demoStruct);
- Console.WriteLine(Convert.ToBase64String(demoStructArray));
- DEMO_STRUCT demoStructGet = new DEMO_STRUCT();
- ConvertByteArrayToStructure(out demoStructGet, demoStructArray);
- Console.WriteLine(demoStructGet.datalen);
- Console.ReadLine();
- }
- }
- }
by Loomman, QQ:28077188, MSN: Loomman@hotmail.com QQ裙:30515563 ☆程序天堂☆ 请尊重作者原创,转载注明来自裂帛一剑博客,谢谢合作。