0

This question is a follow up from Marshalling C# structure to C++ Using StructureToPtr. I have the following struct:

[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];
}

If I try and initialise an array like this:

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

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

I get the following error:The left-hand side of an assignment must be a variable, property or indexer.

What is the correct way to initialise an unsafe array that is part of a struct?

Community
  • 1
  • 1
Seth
  • 8,213
  • 14
  • 71
  • 103

1 Answers1

2

Well the simple approach seems to work:

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

It may not be as far as you're looking for though. Is this a performance-critical piece of code?

This may be better:

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

I can't say I've much experience with unmanaged code, but it's worth at least looking at those options...

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • It is performance sensitive. However will the compiler optimize that with dynamicstate being unsafe? – Seth Oct 05 '12 at 22:39
  • He may PInvoke `C memset` function. It is so fast (although it is not very good with floating-point numbers) –  Oct 05 '12 at 22:40
  • @Seth: I don't like to guess too much with optimizations :) See whether the second one works for you - it may well be faster. – Jon Skeet Oct 05 '12 at 22:40