C Sharp

Interoperability with Unmanaged Code

As you might suspect, unmanaged code is code that isn't controlled by the .NET runtime. Let's be clear about something: this code is still run by the .NET runtime. However, unmanaged code doesn't have the advantages that managed code has, such as garbage collection, a unified type system, and metadata. You might wonder why anyone would want to run unmanaged code in the .NET environment. Well, you wouldn't do it out of choice. Rather, you would do it when faced with circumstances that offer few alternatives. Here are some situations that will make you thankful Microsoft put this feature into .NET: -

  • Managed code calling unmanaged DLL functions Let's say your application needs to interface to a C-like DLL and the company that wrote the DLL isn't adopting .NET as quickly as your company is. In this case, you still need to call into that DLL from a .NET application. I'll cover this very example in Chapter 16, "Querying Metadata with Reflection."
  • Managed code using COM components For the same reason that you might need to continue supporting the ability to call a C-like DLL's functions from your .NET application, you might also need to continue supporting COM components. You do this by creating a .NET wrapper for the COM component so that the managed client thinks it's working with a .NET class. This is also covered in Chapter 16.
  • Unmanaged code using .NET services This is exactly the reverse problem-you want to access .NET from unmanaged code. It's solved using a reciprocal approach: a COM client is fooled into thinking it's using a COM server, which is actually a .NET service of some sort. You'll also see examples of this in Chapter 16.

Summary

Microsoft .NET represents a shift to a computing model in which devices, services, and computers work together to provide solutions for users. Central to that shift is the development of the .NET Framework and the CLR, shown in Figure 2-2 on the following page. The .NET Framework contains the class libraries shared by the languages compiled to run in the CLR. Because C# was designed for the CLR, you can't perform even the simplest tasks in C# without the CLR and .NET Framework class libraries. Understanding the features of these technologies is necessary to get the most out of C#.

-

Figure 2-2 The .NET Framework contains libraries designed to facilitate interoperation between services, devices, and computers.-