2016-11-15 32 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

相关问题