byte []数组到struct的可变长度数组

时间:2015-02-17 21:05:26

标签: c# struct marshalling

我从套接字接收一个字节数组,字节结构只是一个固定宽度字符串的大字符数组。在某些情况下,最后一个字段是动态的(而不是固定长度),我试图将字节元素化为结构。我已经读过可变长度char数组需要是IntPtr,但我还没弄清楚如何用剩余的字节来制作它。我还读过一些文章,我可能需要第二种结构,但仍然无法弄清楚如何正确地制造它。

这是一个site

在结构中处理可变长度char数组的正确方法是什么?

结构:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct Header
{
    #region private member fields

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
    private char[] _f1;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
    private char[] _f2;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
    private char[] _f3;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
    private char[] _f4;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
    private char[] _f5;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
    private char[] _f6;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]
    private char[] _f7;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)]
    private char[] _f8;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)]
    private char[] _f9;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
    private char[] _f10;

    // how would this get filled with a char[] array from the byte array?
    public IntPtr VariableLengthData;

    #endregion
}

功能:

public static Header FromArray(byte[] array)
{
    IntPtr buff = IntPtr.Zero;

    try
    {
        int objsize = Marshal.SizeOf(typeof(Header));
        buff = Marshal.AllocHGlobal(objsize);
        Marshal.Copy(array, 0, buff, objsize);
        var result = (Header)Marshal.PtrToStructure(buff, typeof(HostHeader));

        // the variable length data needs to be filled in somehow
        // but also note that an extra 4 bytes was added to the size
        // of the struct with the IntPtr
        if(objsize < array.Length)
        {
            Marshal.Copy(array, array.Length - objsize, result.VariableLengthData, array.Length - objsize);
        }

        return result;
    }
    finally
    {
        if (buff != IntPtr.Zero)
        {
            Marshal.FreeHGlobal(buff);
            buff = IntPtr.Zero;
        }
    }
}

这很有效 - 但是现在Marshal.SizeOf(headerObj)说它比我尝试将它转换回byte []数组时要小。除此之外,这个解决方案有什么问题吗?

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct Header
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] 
    public char[] Field1;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] 
    public char[] Field2;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] 
    public char[] Field3;

    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
    public char[] Field4;
}

public static Header DeserializeHeader(byte[] data)
{
    int objsize = Marshal.SizeOf(typeof(Header));
    IntPtr buff = Marshal.AllocHGlobal(objsize);
    Marshal.Copy(data, 0, buff, objsize);
    var header = (Header)Marshal.PtrToStructure(buff, typeof(Header));
    Marshal.FreeHGlobal(buff);

    // resize Field4 to hold all the remaining bytes
    if(objsize < data.Length)
    {
        header.Field4 = Encoding.ASCII.GetChars(data, objsize - header.Field4.Length, data.Length - objsize - header.Field4.Length);
    }
    return header;
}

1 个答案:

答案 0 :(得分:10)

不要过于努力使您的C#声明与数据包格式完全匹配。你赞成这个:

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public class Header {
    //....
}

public class Packet {
    public Header Header;
    public byte[] VariableLengthData;
}

现在变得简单了。您可以一举编组标题,只需复制存在的额外字节:

static unsafe Packet FromArray(byte[] data) {
    var hdrsize = Marshal.SizeOf(typeof(Header));
    if (data.Length < hdrsize) throw new ArgumentException();
    Packet result = new Packet();
    // Marshal the header
    fixed (byte* pdata = &data[0]) {
        result.Header = (Header)Marshal.PtrToStructure(new IntPtr(pdata), typeof(Header)); 
    }
    // Copy the rest
    var varsize = data.Length - hdrsize;
    result.VariableLengthData = new byte[varsize];
    Array.Copy(data, hdrsize, result.VariableLengthData, 0, varsize);
    return result;
}

根据需要修改Packet类,你可能想要添加一堆属性来处理char []。