[英]Marshal C++ int array to 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();
我像這樣使用這個函數:
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) { delete[] pArray; } [DllImport("wrapper_demo_d.dll")] public static extern void fnwrapper_release(IntPtr ptr); IntPtr ptr = fnwrapper_intarr(); ... fnwrapper_release(ptr);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.