Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
When .NET 1.0 was first introduced back in 2002, the .NET team was faced with the question of how much support it should provide for interacting with legacy code written outside of the brand new managed runtime. Because the success of the new platform depended, to a large degree, on the adoption rate, the .NET team decided to provide a rich and seamless integration with existing native code. The two primary areas of focus were allowing managed code to call into native code via COM (or vice versa); or, alternatively, call into exported DLL functions. Managed code calling into COM (or vice versa) is called COM interoperability (also called interop) and calls into exported DLL functions are referred to as Platform Invocation Services (P/Invoke). In this chapter, we take a look at how COM interoperability and platform invocation works internally and also some of the most interesting problems that can occur when managed code and native code interact improperly.