Is it safe to use Numeric.Complex with PInvoke? (It doesn't have LayoutKind.Sequential)

I want to use System.Numerics.Complex in an unmanaged PInvoke script. Using ILSpy I noticed that it doesn't have a LayoutKind.Sequential attribute.

/// <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 point to a Complex [] array without converting to a native function expecting a common memory format, ie: Real first, imaginary second? Or perhaps the CLR might violate its real and imaginary attributes for some reason?

+3


source to share


2 answers


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



Even if it isn't: the only reason to reorder the attributes would be due to alignment issues. Since System.Numerics.Complex only has two double members, there would be no reason to replace them. So IMO you are safe.

+1


source


You are fine because this is a structure. It has an implicit [StructLayout] that is consistent. Something you can see from typeof (Complex) .IsLayoutSequential. The same does not apply to the class, it requires an explicit declaration.

And yes, fields can be replaced in the internal representation of an object. But that doesn't matter, since the Pinwaka Marxist has to march the object. It implies Marshal.StructureToPtr () built into the marshaller. Fwiw, this change won't happen because the packaging for two doubles is already optimal. They fit without leaving any extras. Therefore, the marshaller simply creates a pointer to the object and does not have to copy it.



All the good news :)

+1


source







All Articles