.NET Framework Platform Invoke Marshaling structs

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Simple struct

C++ signature:

typedef struct _PERSON
{
    int age;
    char name[32];
} PERSON, *LP_PERSON;

void GetSpouse(PERSON person, LP_PERSON spouse);

C# definition

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public struct PERSON
{
    public int age;
    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
    public string name;
}

[DllImport("family.dll", CharSet = CharSet.Auto)]
public static extern bool GetSpouse(PERSON person, ref PERSON spouse);

Struct with unknown size array fields. Passing in

C++ signature

typedef struct
{
    int length;
    int *data;
} VECTOR;

void SetVector(VECTOR &vector);

When passed from managed to unmanaged code, this

The data array should be defined as IntPtr and memory should be explicitly allocated with Marshal.AllocHGlobal() (and freed with Marshal.FreeHGlobal() afterwords):

[StructLayout(LayoutKind.Sequential)]
public struct VECTOR : IDisposable
{
    int length;
    IntPtr dataBuf;

    public int[] data
    {
        set
        {
            FreeDataBuf();
            if (value != null && value.Length > 0)
            {
                dataBuf = Marshal.AllocHGlobal(value.Length * Marshal.SizeOf(value[0]));
                Marshal.Copy(value, 0, dataBuf, value.Length);
                length = value.Length;
            }
        }
    }
    void FreeDataBuf()
    {
        if (dataBuf != IntPtr.Zero)
        {
            Marshal.FreeHGlobal(dataBuf);
            dataBuf = IntPtr.Zero;
        }
    }
    public void Dispose()
    {
        FreeDataBuf();
    }
}

[DllImport("vectors.dll")]
public static extern void SetVector([In]ref VECTOR vector);

Struct with unknown size array fields. Receiving

C++ signature:

typedef struct
{
    char *name;
} USER;

bool GetCurrentUser(USER *user);

When such data is passed out of unmanaged code and memory is allocated by the unmanaged functions, the managed caller should receive it into an IntPrt variable and convert the buffer to a managed array. In case of strings there is a convenient Marshal.PtrToStringAnsi() method:

[StructLayout(LayoutKind.Sequential)]
public struct USER
{
    IntPtr nameBuffer;
    public string name { get { return Marshal.PtrToStringAnsi(nameBuffer); } }
}

[DllImport("users.dll")]
public static extern bool GetCurrentUser(out USER user);


Got any .NET Framework Question?