Marshal C ++ int数组到C#
我想整理一系列从C ++到C#的整数。 我有一个非托管的C ++ DLL,其中包含:
DLL_EXPORT int* fnwrapper_intarr() { int* test = new int[3]; test[0] = 1; test[1] = 2; test[2] = 3; return test; }
标题extern "C" DLL_EXPORT int* fnwrapper_intarr();
声明extern "C" DLL_EXPORT int* fnwrapper_intarr();
然后我使用pinvoke将其编组为C#:
[DllImport("wrapper_demo_d.dll")] [return: MarshalAs(UnmanagedType.SafeArray)] public static extern int[] fnwrapper_intarr();
我使用这样的function:
int[] test = fnwrapper_intarr();
但是,在程序执行期间,我收到以下错误: SafeArray cannot be marshaled to this array type because it has either nonzero lower bounds or more than one dimension.
我应该使用什么数组类型? 或者是否存在编组数组或整数向量的方式?
[的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);
您还需要在非托管Dll中编写Release函数,该函数删除由fnwrapper_intarr创建的指针。 此函数必须接受IntPtr作为参数。
DLL_EXPORT void fnwrapper_release(int * pArray) { 删除[] pArray; } [的DllImport( “wrapper_demo_d.dll”)] public static extern void fnwrapper_release(IntPtr ptr); IntPtr ptr = fnwrapper_intarr(); ... fnwrapper_release(PTR);