Kate Gregory's Blog
Sunday, 19 December 2010
PInvoke Signatures: "it compiled ok" is not enough
Many people really don't understand where P/Invoke signatures come from, or what they mean. They head over to
, 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
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.
Seen and Recommended
Sunday, 19 December 2010 12:10:28 (Eastern Standard Time, UTC-05:00)
Comments are closed.
© Copyright 2018 Kate Gregory
Theme design by
newtelligence dasBlog 2.3.9074.18820
| Page rendered at Monday, 18 June 2018 07:34:03 (Eastern Daylight Time, UTC-04:00)
On this page....
Pluralsight Free Trial
Click Start a FREE 10-Day trial
Home - Gregory Consulting Limited
Visual C++ on MSDN
Office 12 and VSTO
Seen and Recommended
Visual Studio 11
Visual Studio 2008
Visual Studio 2010
Visual Studio 2013
Visual Studio 2015
Visual Studio 2017