编组 const float** 的正确方法是什么?
What's the correct way to marshal a const float**?
我正在尝试读取通过从 C# 调用 dll 函数创建的数组。当我打印出数组的内容时,它实际上充满了垃圾。
我怀疑这是因为我错误地将 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);
因为无法提前告诉封送拆收器数组的大小,所以您必须手动复制数组。所以 out IntPtr
是正确的。
请注意,您将遇到非常大的数组问题。参见 https://msdn.microsoft.com/en-us/library/hh285054(v=vs.110).aspx and How 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);
我正在尝试读取通过从 C# 调用 dll 函数创建的数组。当我打印出数组的内容时,它实际上充满了垃圾。
我怀疑这是因为我错误地将 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);
因为无法提前告诉封送拆收器数组的大小,所以您必须手动复制数组。所以 out IntPtr
是正确的。
请注意,您将遇到非常大的数组问题。参见 https://msdn.microsoft.com/en-us/library/hh285054(v=vs.110).aspx and How 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);