Saturday, January 01, 2011

“I got your P/Invoke… right here…” But is it right?

Kate Gregory's Blog - 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. …

…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.”

I’ve been following the Windows API Code Pack for forever (since it was the Vista Bridge project…) and I never thought to use it as Kate suggests, as a P/Invoke Reference. In hindsight using it as such seems so logical. I mean that’s the whole purpose for the code pack, to bridge some of the the managed/unmanaged Windows worlds. So dugh, it’s just FULL of yummy P/Invoke’ness! :P


Related Past Post XRef:
Windows API Code Pack v1.1 Released (Think “Bug fix, new Shell/Thumbnail/Preview features, VS2010, xUnit, string localization, signed assemblies and more” release)
More Windows Code Pack and Windows 7 developing delightfulness
Windows 7 Code Pack v1.0 Released – Managed code to help get at the yummy Windows 7 filling…
Bridging to Managed Windows 7 Development – Vista Bridge to Windows Code Pack

.Net, Native, P/Invoke marshaling just like magic… “Marshaling with C# Pocket Reference” (Think “Marshalling Guide for the Busy Dev Guy”)
Signature/Data Type Conversion P/Invoke Cheat Sheet – aka What do you convert a wChar_t to .Net?
Marshall Fixed Length TCHAR Strings between Managed and Unmanaged Code

The PInvoke Interop Assistant Source is now on CodePlex
The PInvoke tool you've been looking for all this time... the "PInvoke Interop Assistant"

No comments: