我花了很多时间寻找解决方案,但仍然没有找到它。
我有2个班级:
[StructLayout(LayoutKind.Sequential)]
public class Result
{
public int Number;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4)]
public string Name;
public int Size;
}
[StructLayout(LayoutKind.Sequential)]
public class CoverObject
{
public int NumOfResults;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 4)]
public Result[] Results;
}
我期望命令Marshal.SizeOf(typeof(CoverObject))
将返回52,但不是,它只是20。因此,我后来使用的所有编组和解组都不起作用。
看起来它只计算Result类中的第一个成员(Number)。我做错了吗?
答案 0 :(得分:12)
将您的班级更改为结构
[StructLayout(LayoutKind.Sequential)]
public struct Result
{
public int Number;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 4)]
public string Name;
public int Size;
}
[StructLayout(LayoutKind.Sequential)]
public struct CoverObject
{
public int NumOfResults;
[MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 4)]
public Result[] Results;
}
其他地方:
Marshal.SizeOf(typeof(CoverObject)) // it will return 52