P/Invoke Signature Generator
If you ever needed to call a Win32 function from .NET code, you know the dreaded feeling. You fire up MSDN and start looking for the function signature, hoping it doesn't invent a new pattern of parameter passing, returning a value and calling back a function you specify. And while you're at it, you still have to figure out what the function is expecting at offset 0x20 from the beginning of the input buffer when the value of the dwExtendedFlags parameter is non-zero.
This tedious process has long ago come to an end with the advent of PInvoke.net, a free Wiki-like developer portal which targets the problem of generating P/Invoke signatures (it also features a cool Visual Studio add-in). For example, here's the signature for CoMarshalInterThreadInterfaceInStream (one of COM's longest API names):
That's all fun and games, but it won't help you in two particularly annoying cases:
- The signature for the API you're looking for is not in the database. (For example, ConvertSecurityDescriptorToStringSecurityDescriptor or AccessCheckAndAuditAlarm);
- You're not trying to use a Win32 API, but rather a function in a third-party (non MS) or your own DLL.
For these scenarios, you had to either perform the conversions by hand or resort to old third-party commercial conversion software (I was only able to find the P/Invoke wizard, last updated around May 2004). I admit, I never tried the latter. Oftentimes I was frustrated enough to just give up the P/Invoke interop approach and go ahead and write a C++/CLI bridge assembly instead (which has the interesting advantages and disadvantages which might be the subject of a future post :-)).
However, these days are over now. In the January 2008 issue of the MSDN Magazine, Yi Zhang and Xiaoying Guo have published a CLR Inside Out column on marshaling between managed and unmanaged code. In that column, they introduce the P/Invoke Interop Assistant, an automatic GUI and command-line utility for converting between managed and unmanaged signatures (in both directions). This conversion, of course, is not limited just to Windows signatures; give the tool a snippet of your own C header files and it will dutifully convert them to pretty-printed C# [DllImport]'s.
This tool has helped me already, and I plan to continue using it in my projects. It also has the great advantage of working perfectly even if you're not connected to the Internet.
It takes annoying long to load (about 30 seconds on my laptop), but when it's loaded you can see the signature for most Windows APIs:
And of course translate your own code snippets: