无法转换字节数组C#中的结构

时间:2016-01-02 11:06:29

标签: c# arrays byte structure

我在将这些结构转换为字节数组时遇到问题:

[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;
    }

我在使用&#34; StructToByteArray&#34;时遇到了这个异常。方法:

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

想法?请不要只发布解决方案,但更多的解释是:D。 问候。

1 个答案:

答案 0 :(得分: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

...也许你没有初始化数组字段&#34; Key&#34; &安培; &#34;帐户名&#34;或者你没有正确地初始化它们。值总是必须是61个字符大小。