我有一個轉換的字節數組的類C#函數的類,因爲它的類型:轉換爲字節數組包含在C#中的字節數組
IntPtr buffer = Marshal.AllocHGlobal(rawsize);
Marshal.Copy(data, 0, 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.
我猜測,使用固定的陣列將是一個解決方案,但是也可以在不需要使用不安全代碼的情況下完成。
你可以使用一個二進制串行器/解串器呢? http://mikehadlow.blogspot.com/2006/11/using-memorystream-and-binaryformatter.html – 2010-05-02 23:22:15
你可以給你更多的背景知識嗎?如果可能的話,使用內置的序列化類將爲您節省很多頭痛的問題。 – ChaosPandion 2010-05-02 23:29:44