2016-11-15 111 views
1

我試圖讀取一個數組,它是由C#編寫的一個dll函數創建的。當我打印出陣列的內容時,它實際上已經是垃圾了。編組const float **的正確方法是什麼?

我懷疑這是因爲我錯誤地將const float**編爲out IntPtr。你如何正確編組const float**

DLL C++接口

int Foo(void *objPtr, uint64_t *resultLen, const float **result); 

DLL導入語句

[DllImport("foo.dll", CharSet = CharSet.Auto)] 
public static extern int Foo(IntPtr objPtr, out ulong resultLen, out IntPtr result); 

長途區號

IntPtr objPtr = getObj(); 
IntPtr result; 
ulong resultLen; 
int output = Foo(objPtr, out resultLen, out result); 
+0

調用該函數 –

+0

你可以考慮使用C++/CLI而不是P的例子所示的C++代碼/調用 –

回答

3

因爲無法提前告知編組器的大小,所以您必須手動複製陣列。所以out IntPtr是正確的。

請注意,你有一個非常大的數組的問題。見https://msdn.microsoft.com/en-us/library/hh285054(v=vs.110).aspxHow to get around Marshal.Copy (32bit) length limit?。這段代碼將使用int作爲結果數組的長度。您需要弄清楚在特定情況下要做什麼。

還要注意你的DLL必須負責釋放它分配的內存。見Release unmanaged memory from managed C# with pointer of it

IntPtr objPtr = getObj(); 
IntPtr result; 
int resultLen; 

// call your external function 
int output = Foo(objPtr, out resultLen, out result); 

// create an array to hold the output data 
float[] array = new float[resultLen]; 

// copy the data 
Marshal.Copy(result, array, 0, resultLen); 

// since the memory was allocated by the DLL only it knows how to free it 
// so call the free function exported by the DLL 
FreeBufferAfterFoo(result); 
+0

感謝您的回答。既然你說'out IntPtr'是正確的,因爲我的代碼中有相當於你的額外代碼,所以在我的數組中有垃圾的原因似乎與我編組'const float ** '。我提高了你的答案,因爲這是非常豐富的,儘管我的問題還沒有解決。如果有一段時間沒有任何其他答案可能會有不同的建議,我將編輯問題只是關於編組'const float **',我會接受你的答案。再次感謝 :) – cycloidistic

相關問題