0

这个问题是从Marshalling C# structure 到 C++ Using StructureToPtr的后续问题。我有以下结构:

[StructLayout(LayoutKind.Explicit, Size = 120, CharSet = CharSet.Unicode)]
public unsafe struct DynamicState
{
    [FieldOffset(0)]
    public fixed double Position[3];

    [FieldOffset(24)]
    public fixed double Velocity[3];

    [FieldOffset(48)]
    public fixed double Acceleration[3];

    [FieldOffset(72)]
    public fixed double Attitude[3];

    [FieldOffset(96)]
    public fixed double AngularVelocity[3];
}

如果我尝试像这样初始化一个数组:

var dynamicState = new DynamicState();
double[] array = new double[] { 1, 2, 3 };

fixed (double* pArray = array)
{
    dynamicState.Acceleration = pArray;
}

我收到以下错误:The left-hand side of an assignment must be a variable, property or indexer

初始化作为结构一部分的不安全数组的正确方法是什么?

4

1 回答 1

2

那么简单的方法似乎有效

for (int i = 0; i < 3; i++)
{
    dynamicState.AngularVelocity[i] = array[i];
}

不过,它可能不像您要寻找的那样远。这是一段性能关键的代码吗?

可能会更好:

Marshal.Copy(array, 0, new IntPtr(dynamicState.AngularVelocity), array.Length);

我不能说我对非托管代码有很多经验,但至少值得看看这些选项......

于 2012-10-05T22:34:44.337 回答