我正在从套接字接收一个字节数组,这些字节的结构只是一个固定宽度字符串的大型字符数组。在某些情况下,最后一个字段是动态的(而不是固定长度),我正在尝试将字节编组为一个结构体。我已经读到可变长度的char数组需要使用IntPtr,但我还没有弄清楚如何用剩余的字节进行编组。我也在一些文章中读到可能需要第二个结构体,但仍然无法正确地进行编组。
以下是其中一个网站。
如何正确处理结构体中的可变长度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;
}
}
}
这个方案有效 - 但现在当我尝试将其转换回byte[]数组时,Marshal.SizeOf(headerObj)说它比实际小。除此之外,这个方案还有什么问题吗?
[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;
}
Encoding.ASCII.GetString(array,160,array.Length-160)
- EZI