C++ C#数组互操作
from 20.4.2 Managed arrays using P/Invoke default array marshalling
In the P/Invoke default marshalling scheme, one needs to designate whether the invoked function will treat a managed array parameter as input, output, or both. When the function is invoked, the CLR allocates a separate chunk of memory as big as the given managed array, which is automatically released at the end of the function call. If the array parameter is marked as being input, the content of the managed array is copied into this buffer when the call is made. Correspondingly, if the array parameter is marked as being output, the contents of the reserved buffer are copied back into the managed array after the call returns. A pointer to this buffer is passed to the native function.
The reason for allocating a separate buffer is to leave the CLR free to relocate the managed array object during garbage collection. If the overhead caused by the copying is causing a significant performance penalty, consider pinning the managed array and passing a direct reference as described in the next section.
C#向C++传递数组时,CLR会创建数组的副本,这会影响效率,此时可以考虑pin数组和传递引用
*强调内容*from 20.4.3 Managed arrays using pinning
using pinning, thus avoiding the CLR making copies of the arrays passed as parameters.
On the method signature level the only difference to the version using P/Invoke default marshalling is the “unsafe” quantifier, which is required because we are handling pointers.
Also the intermediary class method looks a little different from the default marshalling example – the method is expecting an IntPtr as the parameter type.
实质上就是传指针
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/224964.html原文链接:https://javaforall.net
