Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
938 views
in Technique[技术] by (71.8m points)

Mapped c++ struct to c# struct

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...