C#中结构体与字节流互相转换

来源:互联网 发布:知乎童谣诈骗事件始末 编辑:程序博客网 时间:2024/06/14 01:44

注:本文的内容是摘自http://blog.csdn.net/huxiangyang4/article/details/5853247的部分内容,感谢这篇博客的博主的热心分享。

 class Converter    {        //Structure转为Byte数组,实现了序列化        public static Byte[] StructToBytes(Object structure)        {            Int32 size = Marshal.SizeOf(structure);            Console.WriteLine(size);            IntPtr buffer = Marshal.AllocHGlobal(size);            try            {                Marshal.StructureToPtr(structure, buffer, false);                Byte[] bytes = new Byte[size];                Marshal.Copy(buffer, bytes, 0, size);                return bytes;            }            finally            {                Marshal.FreeHGlobal(buffer);            }        }        //Byte数组转为Structure,实现了反序列化        public static Object BytesToStruct(Byte[] bytes, Type strcutType)        {            Int32 size = Marshal.SizeOf(strcutType);            IntPtr buffer = Marshal.AllocHGlobal(size);            try            {                Marshal.Copy(bytes, 0, buffer, size);                return Marshal.PtrToStructure(buffer, strcutType);            }            finally            {                Marshal.FreeHGlobal(buffer);            }        }    }


0 0
原创粉丝点击