using System.Runtime.InteropServices; //WinAPI引用命名空间 /// <summary> /// 将Byte转换为结构体类型 /// </summary> /// <param name="bytes"></param> /// <param name="type"></param> /// <returns></returns> public static object ByteToStruct(byte[] bytes, Type type) { int size = Marshal.SizeOf(type); if (size > bytes.Length) { return null; } //分配结构体内存空间 IntPtr structPtr = Marshal.AllocHGlobal(size); //将byte数组拷贝到分配好的内存空间 Marshal.Copy(bytes, 0, structPtr, size); //将内存空间转换为目标结构体 object obj = Marshal.PtrToStructure(structPtr, type); //释放内存空间 Marshal.FreeHGlobal(structPtr); return obj; }