Mapped c++ struct to c# struct

我们两清 提交于 2019-12-11 19:42:27

问题


I am having trouble mapping the following c++ struct in c# for memory mapping purposes.

typedef struct
{
DWORD Data1;
DWORD Data2;
double AverageData[2];
DWORD NumData[2];
} DIRECTIONAL_STATS;

typedef struct
{
DIRECTIONAL_STATS DirectionStats[2];
char  Name[100];
int   StatLength;
} OTHER_STATS;


typedef struct
{
OTHER_STATS SystemStat[64][2];

long LastUpdate;
}STATS;

Can someone please shed some lights on how to achieve the mapping? Mapping from c++ type to c# type is fine for me.

However, I don't have any clue how to map nested struct and the explicit array size required.

Update 1: Managed to map to following c# code:

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct STATS
    {
        [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 128)]
        public OTHER_STATS[] SystemStat; //64x2
        public long LastUpdate;            
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
    public struct OTHER_STATS
    {
        [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 2)]
        public DIRECTIONAL_STATS[] DirectionStats;

        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 100)]
        public char[] Name;
        public int StatLength;
    }       

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
     public struct DIRECTIONAL_STATS
    {
        public UInt16 Data1;
        public UInt16 Data2;

        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
        public double[] AverageData;

        [MarshalAs(UnmanagedType.ByValArray, SizeConst = 2)]
        public UInt16[] NumColdRes;
    }        

Unsure about the following mapping since it is a multidimensional arrays.

public SENTRY_PERFORMANCE_STATS[] Sentry; //64x2

Using the above mapping, it is able to run without any exception, however, the data mapped into OTHER_STATS are all wrong.

Can anyone see what I have done wrong?

Thanks.

来源:https://stackoverflow.com/questions/19019499/mapped-c-struct-to-c-sharp-struct

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