如何将对象数组传递给非托管代码?
我试图将对象数组从 C# 传递到非托管 C++,但似乎没有任何效果。
编译器不会让我假装该数组是 IntPtr。将数组转换为 IntPtr 不起作用。我尝试传递固定数据的地址,但这也不起作用。
我只需要传递一个指向数组开头的指针,结果发现这是非常困难的。
有什么建议或链接吗?谢谢!
I'm trying to pass an array of objects from C# to unmanaged C++, and nothing seems to work.
The compiler won't let me pretend the array is an IntPtr. Casting the array to an IntPtr doesn't work. I've tried to pass the address of pinned data, but this didn't work either.
I just need to pass a pointer to the beginning of the array, and this is turning out to be incredibly difficult.
Any suggestions or links? Thanx!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最终起作用的是:
What finally worked:
可以转换为 void 指针吗?确保对象数组已固定。
Can you cast to a void pointer? Be sure the array of objects is pinned.
在 C#/托管方法签名中,使用 [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)]... 标记输入参数,
然后像往常一样调用它。此外,在非托管代码中,您可以修改此数组。我建议您发送一个额外的 int 告诉非托管代码数组的大小是多少,以防止“数组越界”修改。
In your C#/Managed method signature, mark the input parameter with [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)]...
Then call it as you did always. Also, inside the unmanaged code, you can modify this array. I suggest that you send in an extra int telling the unmanaged code what the size of the array is to prevent “array out of bound” modification.