开发者

Without using "fixed", how do I access values of an array within a struct?

I'm doing C++ --> C# interop stuff an开发者_开发问答d I have a bunch of structs that contain each other like Matryoshka dolls. The problem is that one of these 'nestings' takes the form of a fixed length array:

typedef struct tagBIRDREADING
{
    BIRDPOSITION    position;
    BIRDANGLES      angles;
    BIRDMATRIX      matrix;
    BIRDQUATERNION  quaternion;
    WORD            wButtons;
}
BIRDREADING;

typedef struct tagBIRDFRAME
{
    DWORD           dwTime;
    BIRDREADING     reading[BIRD_MAX_DEVICE_NUM + 1];
}
BIRDFRAME;

Following the hallowed teachings of Eric Gunnerson, I did the following in C#:

[StructLayout(LayoutKind.Sequential, Pack = 0)]
public struct BIRDREADING
{
    public BIRDPOSITION position;
    public BIRDANGLES angles;
    public BIRDMATRIX matrix;
    public BIRDQUATERNION quaternion;
    public ushort wButtons;
}

[StructLayout(LayoutKind.Sequential, Size = 127)]
public struct BIRDREADINGa
{
    public BIRDREADING reading;
}

public struct BIRDFRAME
{
    public uint dwTime;
    public BIRDREADINGa readings; 
}

My question is, how do I access each of the 127 instances of BIRDREADING contained within BIRDREADINGa and therefore BIRDFRAME? Or have I gone terrible wrong?


I think you just want this:

[StructLayout(LayoutKind.Sequential)]
public struct BIRDFRAME
{
    public uint dwTime;
    [MarshalAs(UnmanagedType.ByValArray, SizeConst=127)] 
    public BIRDREADING[] readings; 
}


To access all those instances without using an array you need to use an unsafe block to grab the address of the "fake array" you set up, and then use pointer arithmetic. It's going to get ugly:

public struct BIRDREADINGa
{
    public BIRDREADING reading;

    public BIRDREADING GetReading(int index)
    {
        unsafe
        {
            fixed(BIRDREADING* r = &reading)
            {
                return *(r + index);
            }
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜