Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

You are fine because this is a struct. It has an implied [StructLayout] that's sequential. Something you can see from typeof(Complex).IsLayoutSequential. The same is not true for a class, it requires an explicit declaration.

And yes, fields can get swapped in the internal representation of the object. But that won't matter since the pinvoke marshaller must marshal the object. There's an implied Marshal.StructureToPtr() built into the marshaller. Fwiw, this swapping won't happen because the packing for two doubles is already optimal. They fit without leaving any padding. So the marshaller just creates a pointer to the object and won't have to copy it.

All good news :)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top