结构的马歇尔阵列(Marshall array of structures)

2019-07-23 10:52发布

我花了很多时间去寻找解决方案,但仍然没有找到它。

我有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类的第一件(数量)。 我做了什么错事?

Answer 1:

改变你的类结构

[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


文章来源: Marshall array of structures