元帅C ++ int数组到C# [英] Marshal C++ int array to C#
问题描述
我想从元帅C ++的int到C#的数组。我有一个包含非托管C ++ DLL:
DLL_EXPORT为int * fnwrapper_intarr()
{
为int *测试=新INT [3]; 试验[0] = 1;
试验[1] = 2;
测试[2] = 3; 回归测试;
}
与声明中的头的externCDLL_EXPORT为int * fnwrapper_intarr();
我然后使用的PInvoke它元帅到C#:
函数[DllImport(wrapper_demo_d.dll)]
[返回:的MarshalAs(UnmanagedType.SafeArray)
公共静态外部INT [] fnwrapper_intarr();
和我使用的功能,像这样:
INT [] =测试fnwrapper_intarr();
不过,在程序执行过程中出现了以下错误: safearray之所以不能封送到该数组类型,因为它不是非零下限或多个维度
我应该用什么数组类型?或者是有编组数组或整数向量的bettery方式?
函数[DllImport(wrapper_demo_d.dll)]
公共静态外部的IntPtr fnwrapper_intarr();IntPtr的PTR = fnwrapper_intarr();
INT []结果=新INT [3];
Marshal.Copy(PTR,结果,0,3);
您也需要写非托管的DLL,这将删除fnwrapper_intarr创建指针释放功能。此函数必须接受的IntPtr作为参数。</ P>
DLL_EXPORT无效fnwrapper_release为(int *粒子阵列)
{
删除[]粒子阵列;
}函数[DllImport(wrapper_demo_d.dll)]
公共静态外部无效fnwrapper_release(IntPtr的PTR);IntPtr的PTR = fnwrapper_intarr();
...
fnwrapper_release(PTR);
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?
[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);
这篇关于元帅C ++ int数组到C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!