Search code examples
clrcomplextypememory-layout

Safe to use Numeric.Complex with PInvoke? (It does not have LayoutKind.Sequential)


I want to use System.Numerics.Complex in an unmanaged PInvoke scenario. Using ILSpy, I noticed it does not have a LayoutKind.Sequential attribute assigned.

/// <summary>Represents a complex number.</summary>
[Serializable]
public struct Complex : IEquatable<Complex>, IFormattable
{
    private double m_real;
    private double m_imaginary;
    ...

Is it safe to give a pointer to an Complex[] array without conversion to a native function expecting the common memory layout, ie.: Real first, imaginary second? Or could the CLR possibly disorder its real and imaginary attributes for some reason?


Solution

  • LayoutKind.Sequential is default for all major .NET compiler: http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.layoutkind.aspx

    Even if it wouldn't: theonly reason to alter the order of attributes would be for alignment issues. Since System.Numerics.Complex does only have two double members there would be no reason to exchange them. So IMO you are safe.