Mapped c++ struct to c# struct

2019-09-16 09:59发布

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.

0条回答
登录 后发表回答