马歇尔结构阵列
本文关键字:阵列 结构 马歇尔 | 更新日期: 2023-09-27 18:05:47
我花了很多时间寻找解决办法,但仍未找到。
我有两个类:
[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)。我做错什么了吗?
将类更改为structs
[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