Chapter 21. Interoperability
C# programs sometimes need to use software components that are not implemented in .NET. The majority of services Windows provides are designed to be used from unmanaged code (i.e., code that does not use the CLR’s managed execution environment), and although the .NET Framework class library provides wrappers for many of these, you may want to use a feature for which no managed API exists. Also, you or your organization may have existing unmanaged code that you’d like to be able to use from C#. The CLR supports all this through its interoperability features (or interop, for short) that make it possible to use native (i.e., unmanaged) APIs from C#.
Interop supports three main categories of native API. You can call into native DLLs, which is how most of the Win32 API is presented. (This form of interop is called Platform Invoke, often abbreviated to P/Invoke.) You can also use the Component Object Model (COM), which supports object-based native APIs. Finally, starting with Windows 8, we have the Windows Runtime, and although that’s based on COM, .NET 4.5 offers specialized support that goes beyond basic COM interop to help make Windows Runtime classes feel like a more natural fit with C# than older COM APIs.
Regardless of which of the three forms you’re using, there are certain aspects of interop common to all of them. I’ll describe these before moving on to the technology-specific features.
Calling Native Code
No matter which style of native API you use, interop ...
Get Programming C# 5.0 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.