8.4 Mastering Unmanaged APIs with PINVOKE.NET
When writing code in a language like C# or Visual Basic, you have first-class access to all .NET-based (or “managed”) APIs. But often you need to access unmanaged APIs to accomplish a task. These unmanaged APIs might be part of Win32 (e.g., one of the 7,000+ APIs added to Windows Vista that don’t have coverage in the .NET Framework at the time of writing) or third-party components. Fortunately, the Common Language Runtime’s Platform Invoke technology, PInvoke, enables managed code to call any static DLL exports.
Unfortunately, using PInvoke correctly is extremely difficult. To call an API, you must declare its signature in managed code. This signature tells the CLR everything about the API to call: its module, name, number and type of parameters, calling convention, and so on. But if you don’t declare the signature with the right mixture of custom attributes and data types, you can easily cause the call to fail, and maybe even corrupt memory.
Thanks to PINVOKE.NET (http://www.pinvoke.net), you no longer need to be an expert in CLR interoperability to use PInvoke, nor do you need to create your PInvoke signatures from scratch. PINVOKE.NET is a Wiki where anyone can find or contribute PInvoke signatures, their associated user-defined types, and other interoperability-related information. The site is run by Adam Nathan from Microsoft, author of .NET and COM: The Complete Interoperability Guide (Sams) and original member of the team that created ...
Get Windows Developer Power Tools now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.