我有一个C#函数将字节数组转换为类,给定它的类型:
IntPtr buffer = Marshal.AllocHGlobal(rawsize); Marshal.Copy(data,buffer,rawsize); object result = Marshal.PtrToStructure(buffer,type); Marshal.FreeHGlobal(buffer);
我使用顺序结构:
[StructLayout(LayoutKind.Sequential)] public new class PacketFormat : Packet.PacketFormat { }
这很好,直到我试图转换为包含字节数组的结构/类.
[StructLayout(LayoutKind.Sequential)] public new class PacketFormat : Packet.PacketFormat { public byte header; public byte[] data = new byte[256]; }
Marshal.SizeOf(type)返回16,它太低(应该是257)并导致Marshal.PtrToStructure失败并出现以下错误:
Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
解决方法
不需要不安全的代码:
[StructLayout(LayoutKind.Sequential)] public struct PacketFormat { public byte header; [MarshalAs(UnmanagedType.ByValArray,SizeConst = 256)] public byte[] data; }