不使用“fixed”,如何在结构中访问数组的值?

时间:2011-04-15 10:57:17

标签: c# arrays pinvoke marshalling struct

我正在做C ++ - > C#interop stuff和我有一堆结构,像Matryoshka娃娃一样互相包含。问题是这些“嵌套”中的一个采用固定长度数组的形式:

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;

hallowed teachings of Eric Gunnerson之后,我在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; 
}

我的问题是,如何访问BIRDREADING中包含的BIRDREADINGa的127个实例中的每一个,因此BIRDFRAME?或者我出错了?

2 个答案:

答案 0 :(得分:4)

我想你只想要这个:

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

答案 1 :(得分:0)

要在不使用数组的情况下访问所有这些实例,您需要使用不安全的块来获取您设置的“假数组”的地址,然后使用指针算法。它会变丑:

public struct BIRDREADINGa
{
    public BIRDREADING reading;

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