When passing a managed byte[] array through PInvok

2019-01-11 10:22发布

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?

3条回答
Animai°情兽
2楼-- · 2019-01-11 10:23

according to msdn Marshaling Arrays of Types only an array passed by reference can be written to by unmanaged code. So it appears that you must declare the array parameter [out] or [in,out] if you want to fill it in on the unmanaged side.

This page http://msdn.microsoft.com/en-us/library/aa719896(VS.71).aspx manages to go on and on without ever explicitly saying that the marshaller pins the arrays during the call from managed to unmanaged, but much of what it describes wouldn't work if the marshaller didn't pin.

查看更多
家丑人穷心不美
3楼-- · 2019-01-11 10:25

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

Longer Answer:

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.

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

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

查看更多
聊天终结者
4楼-- · 2019-01-11 10:44

Sorry to answer my own question but I believe if the type is blittable, as byte[] is, then the array would be pinned while being marshalled by the runtime, so no pinning would be needed. An object on the other time would be different. Please correct me if I'm wrong.

查看更多
登录 后发表回答