2010-05-02 53 views
6

我有一個轉換的字節數組的類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.

我猜測,使用固定的陣列將是一個解決方案,但是也可以在不需要使用不安全代碼的情況下完成。

+0

你可以使用一個二進制串行器/解串器呢? http://mikehadlow.blogspot.com/2006/11/using-memorystream-and-binaryformatter.html – 2010-05-02 23:22:15

+0

你可以給你更多的背景知識嗎?如果可能的話,使用內置的序列化類將爲您節省很多頭痛的問題。 – ChaosPandion 2010-05-02 23:29:44

回答

5

無需不安全代碼:

[StructLayout(LayoutKind.Sequential)] 
public struct PacketFormat 
{ 
    public byte header; 
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)] public byte[] data; 
} 
+0

謝謝,這工作! – Matt 2010-05-03 16:49:26

4

您需要使用固定大小的字節數組。

[StructLayout(LayoutKind.Sequential)] 
public unsafe struct PacketFormat 
{ 
    public byte header; 
    public fixed byte data[256]; 
} 
+0

我的問題是它是否可以在沒有不安全代碼的情況下完成。 – Matt 2010-05-03 11:13:19