Monday, 15 August 2011

c# - When passing a managed byte[] array through PInvoke to be filled in by Win32, does it need to be pinned? -



c# - When passing a managed byte[] array through PInvoke to be filled in by Win32, does it need to be pinned? -

suppose you're calling win32 function fill in byte array. create array of size 32, empty. pass in win32 function filled int, , utilize later in managed code. there exist chance byte array might moved or overwritten in between time allocated , filled in win32 function?

short answer: no, pinning not necessary in case

longer answer:

the clr automatically pin references managed objects when cross pinvoke boundary. pinvoke function exits reference unpinned. in situations having native function fill byte[] no manually pinning necessary because object used native code during function call.

manually pinning of array becomes necessary if native code caches managed pointer. when happens must manually pin array until native code no longer needs pointer. in case presume pointer not cached hence it's not necessary pin

reference - http://msdn.microsoft.com/en-us/magazine/cc163910.aspx#s2

c# .net visual-studio clr pinvoke

No comments:

Post a Comment