2016-01-02 32 views
0

我有,而將這些結構的字節數組問題:無法轉換結構中的字節數組C#

[StructLayout(LayoutKind.Sequential)] 
/// <summary> 
/// Packet structure, type 1 (SEND) 
/// </summary> 
internal struct PACKET_SEND 
{ 
    /// <summary> 
    /// Packet Type: 0 for notifications, 1 for status, 2 for login and auth. 
    /// </summary> 
    public Byte Type; 
    /// <summary> 
    /// Packet Key: select it from Packets class. 
    /// </summary> 
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 61)] 
    public char[] Key; 
    /// <summary> 
    /// Account Name. 
    /// </summary> 
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 30)] 
    public char[] AccountName; 
    /// <summary> 
    /// Account Status: 0 for offline, 1 for online, 2 for absent, 3 for busy, 4 for invisible. 
    /// </summary> 
    public Byte Status; 
} 

[StructLayout(LayoutKind.Sequential)] 
/// <summary> 
/// Packet structure, type 2 (RECV) 
/// </summary> 
internal struct PACKET_RECV 
{ 
    /// <summary> 
    /// Packet Type: 0 for notifications, 1 for status, 2 for login and auth. 
    /// </summary> 
    public Byte Type; 
    /// <summary> 
    /// Packet Key: select it from Packets class. 
    /// </summary> 
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 61)] 
    public char[] Key; 
    /// <summary> 
    /// Account Name. 
    /// </summary> 
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 30)] 
    public char[] AccountName; 
} 

使用這些功能:

public static T ByteArrayToStructure<T>(byte[] data) where T : struct 
    { 
     GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned); 
     T stuff = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), 
      typeof(T)); 
     handle.Free(); 
     return stuff; 
    } 

    public static byte[] StructToByteArray(object structure) 
    { 
     byte[] buffer = new byte[Marshal.SizeOf(structure)]; 
     GCHandle handle = GCHandle.Alloc(buffer, GCHandleType.Pinned); 
     Marshal.StructureToPtr(structure, handle.AddrOfPinnedObject(), false);//HERE GETS EXCEPTION 
     handle.Free(); 
     return buffer; 
    } 

我收到異常而使用「StructToByteArray」方法:

Type could not be marshaled because the length of an embedded array instance does not match the declared length in the layout. 

想法?請不要只發布解決方案,但解釋會更加讚賞:D。 問候。

+0

當然,你做對了嗎?我做了一個快速測試,它爲我工作。你能展示更多的代碼嗎?順便說一句,我的原代碼沒有顯示此(http://stackoverflow.com/questions/8704161/c-sharp-array-within-a-struct/8704505#8704505),但我建議將'元帥'調用包裝到'嘗試...終於'。 –

回答

0

看看...

Error : Type could not be marshaled because the length of an embedded array instance does not match the declared length in the layout

......還有......

Error on size of class

...也許你不初始化數組字段 「鑰匙」 &「 AccountName「或者你沒有正確初始化它們。值總是必須是61和30個字符。

+0

嘗試一下。我確定密鑰是**總是** 61個字符長度,但AccountName是可變的。所以要「填補」並嘗試。 – Ciavi

+0

@Ciavi你是否嘗試單獨轉換數組?因爲這不應該工作,轉換孔結構正在工作。 –