Many people really don't understand where P/Invoke signatures come from, or what they mean. They head over to pinvoke.net
, which - don't get me wrong - is a hugely important resource, and then blindly paste in whatever they find and try compiling and running their code. Or they use the superbly helpful P/Invoke Interop Assistant
. Again, paste, build, run, works on my machine.
This is a great way to start. The problem is assuming that once one run worked, you're done. You need to read and understand the P/Invoke signature you are using. Especially when you are passing in a pointer, or getting a pointer back, you must know who owns that memory and who will clean it up. Are you handing it over to the native code to manage? Is there a risk your managed code will clean it up before the native code is done with it? Is there a risk the native code will clean it up, and then later the managed code will also try to clean it up? Don't think these things don't happen, they most certainly do.Here's an example
: a long running intermittent bug that was caused by a P/Invoke declaration that said the managed side would clean up, but that should have said the native side would (since the native side did.) And here's a nice summary
of ways to make sure that native resources (like handles) aren't cleaned up too soon by the managed side. Sorry, but you need to understand this stuff in order to interop successfully. That's where the phrase "head spinning interop" came from, after all.
Don't like it? Don't want to learn it? Then use an interop library like the Code Pack
that takes care of those sorts of things for you and exposes an entirely managed interface. Have to learn it whether you want to or not? Consider using the Code Pack as a reference for how to do interop properly. The full source code is available, and nicely commented too.