Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
573 views
in Technique[技术] by (71.8m points)

Marshal C++ int array to C#

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
[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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...