【问题标题】:What's the correct way to marshal a const float**?编组 const float** 的正确方法是什么?
【发布时间】:2016-11-15 02:01:31
【问题描述】:

我正在尝试读取通过调用 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); 

【问题讨论】:

  • 显示了调用函数的示例 C++ 代码

标签: c# pinvoke marshalling


【解决方案1】:

因为没有办法提前告诉封送器数组的大小,所以您必须手动复制数组。所以out IntPtr 是正确的。

请注意,您会遇到非常大的数组的问题。请参阅 https://msdn.microsoft.com/en-us/library/hh285054(v=vs.110).aspx 和 How to get around Marshal.Copy (32bit) length limit? 。这个 sn-p 将使用 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);

【讨论】:

  • 感谢您的回答。既然你说out IntPtr 是正确的,而且我的个人代码中有相当于你的额外代码,那么我的数组中出现垃圾的原因似乎与我编组const float** 的方式无关。我赞成您的回答,因为它提供了非常丰富的信息,尽管我的问题尚未解决。如果一段时间内没有任何其他答案可能有不同的建议,我会将问题编辑为关于编组 const float** 的问题,我会接受您的回答。再次感谢:)
猜你喜欢
  • 2015-04-23
  • 2020-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-22
  • 2017-04-20
  • 1970-01-01
相关资源
最近更新 更多