Marshal C++ int array to C#

Viewed 15796

I would like to marshal an array of ints from C++ to C#. I have an unmanaged C++ dll which contains:

DLL_EXPORT int* fnwrapper_intarr()
{
    int* test = new int[3];

    test[0] = 1;
    test[1] = 2;
    test[2] = 3;

    return test;
}

with declaration in header extern "C" DLL_EXPORT int* fnwrapper_intarr();

I am then using pinvoke to marshal it into C#:

[DllImport("wrapper_demo_d.dll")]
[return: MarshalAs(UnmanagedType.SafeArray)]
public static extern int[] fnwrapper_intarr();

And I use the function like so:

int[] test = fnwrapper_intarr();

However, during program execution I get the following error: SafeArray cannot be marshaled to this array type because it has either nonzero lower bounds or more than one dimension.

What array type should I be using? Or is there a bettery way of marshalling arrays or vectors of integers?

1 Answers
Related