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?

1 Answer 1

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...

Sign up to request clarification or add additional context in comments.

3 Comments

It is performance sensitive. However will the compiler optimize that with dynamicstate being unsafe?
He may PInvoke C memset function. It is so fast (although it is not very good with floating-point numbers)
@Seth: I don't like to guess too much with optimizations :) See whether the second one works for you - it may well be faster.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.