Marshall array of structures

前提是你 提交于 2019-11-29 17:53:17

问题


I've spent a lot of time to look for the solution but still don't find it out.

I have 2 classes:

[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;
}

My expectation that the command Marshal.SizeOf(typeof(CoverObject)) will return 52, but not, it's just 20. Thus, all of marshall and unmarshall that I use later are not working.

Seeming it only counts the first member (Number) in Result class. Did I do anything wrong?


回答1:


Change your classes to 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;
}

some where else:

Marshal.SizeOf(typeof(CoverObject)) // it will return 52


来源:https://stackoverflow.com/questions/15632646/marshall-array-of-structures

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!