Thursday, April 18, 2013

Passing a structure containing a float array from C# to a C++ DLL

For a struct defined in C++ as:

struct MyStruct
{
    float m_aFloatArray1[4];
    float m_aFloatArray2[4];
    float m_aFloatArray3[4];
};

And you want to simply pass the struct from C# straight into C++, you would define the struct on the C# side as:

[StructLayout( LayoutKind.Sequential )]
public struct MyStruct
{
    [MarshalAs( UnmanagedType.ByValArray, ArraySubType = UnmanagedType.R4, SizeConst = 4 )]
    public float[] m_aFloatArray1;
    [MarshalAs( UnmanagedType.ByValArray, ArraySubType = UnmanagedType.R4, SizeConst = 4 )]
    public float[] m_aFloatArray2;
    [MarshalAs( UnmanagedType.ByValArray, ArraySubType = UnmanagedType.R4, SizeConst = 4 )]
    public float[] m_aFloatArray3;
}

Note that this approach only works for fixed size arrays (otherwise things get hairy.)

No comments:

Post a Comment