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

本文关键字:结构体 访问 数组 fixed 何访问 如果不 | 更新日期: 2023-09-27 17:50:12

我正在做c++ -> c#互操作的东西,我有一堆结构体彼此包含像俄罗斯套娃。问题是其中一个"嵌套"采用固定长度数组的形式:

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;

遵循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; 
}

我的问题是,我如何访问BIRDREADINGaBIRDFRAME中包含的BIRDREADING的127个实例中的每个实例?还是我犯了大错?

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

我想你只是想要这个:

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

要在不使用数组的情况下访问所有这些实例,您需要使用一个不安全块来获取您设置的"假数组"的地址,然后使用指针算术。这会很难看的:

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