13

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
  • If you are the author of fnwrapper_intarr, is there anything against returning a safearray (or better as parameter)? Commented Sep 23, 2010 at 9:01

1 Answer 1

21
[DllImport("wrapper_demo_d.dll")]
public static extern IntPtr fnwrapper_intarr();

IntPtr ptr = fnwrapper_intarr();
int[] result = new int[3];
Marshal.Copy(ptr, result, 0, 3);

You need also to write Release function in unmanaged Dll, which deletes pointer created by fnwrapper_intarr. This function must accept IntPtr as parameter.

DLL_EXPORT void fnwrapper_release(int* pArray)
{
    delete[] pArray;
}

[DllImport("wrapper_demo_d.dll")]
public static extern void fnwrapper_release(IntPtr ptr);

IntPtr ptr = fnwrapper_intarr();
...
fnwrapper_release(ptr);
Sign up to request clarification or add additional context in comments.

2 Comments

+1 Great! It worked, except I think it should be Marshal.Copy not Marshal::Copy.
And what should you do if you don't know the size of the array on C# side?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.