在通过的PInvoke传递管理byte []数组由Win32的填写,它需要被寄托?数组、寄托、PInvoke、byte

2023-09-02 01:41:43 作者:你跟緊點

假设你调用一个Win32函数,将填补在你的字节数组。创建大小为32,空数组。然后把它传递到Win32函数被填补INT,在你随后的管理code使用它。不存在的机会字节数组可能移动或覆盖在时间它被分配,它是填充在由Win32函数?

Suppose you're calling a Win32 function that will fill in your byte array. You create an array of size 32, empty. Then pass it in to the Win32 function to be filled int, and use it later in your managed code. Does there exist the chance that the byte array might be moved or overwritten in between the time it was allocated and it is filled in by the Win32 function?

推荐答案

简短的回答:不,钉扎没有必要在这种情况下

Short Answer: No, pinning is not necessary in this case

再回应:

CLR将自动针引用管理对象的跨边界的PInvoke时。只要PInvoke的功能退出参考将取消固定。因此,就像有一个本地函数填补的情况下一个字节[没有手动钉是必要的,因为对象是在函数调用时只使用本土code]。

The CLR will automatically pin references to managed objects when the cross the PInvoke boundary. As soon as the PInvoke function exits the reference will be unpinned. So in situations like having a native function fill a byte[] no manually pinning is necessary because the object is only used by native code during the function call.

手工钉扎阵列如果本地code缓存管理的指针成为必要。发生这种情况时,你必须手动针阵列中,直至本机code不再需要指针。在这种情况下,我presume指针没有缓存,因此它没有必要针

Manually pinning of the array becomes necessary if the native code caches the managed pointer. When this happens you must manually pin the array until the native code no longer needs the pointer. In this case I presume the pointer is not cached hence it's not necessary to pin

参考 - http://msdn.microsoft.com/en-us/magazine/cc163910.aspx#S2