The .NET framework provides several core run-time services to the programs that run within it. For example; Exception Handling and Security. In order for these services to work, the code must provide a minimum level of information to the runtime. Code that executes under the control of the runtime is called Managed Code.
Similarly, the data that is allocated and freed by the .NET runtime’s garbage collector is called Managed Data.
Benefits of CLR:
- Objects are self-describing
- Provides Code-Access-Security
- Assembly based deployment to avoid DDL hell
- Code development made easy
- Side-by-side versioning of reusable components
- Automatic Object Lifetime Management
- Seamless integration between CLR compliant languages
Code that runs outside the runtime is called unmanaged code. COM components, ActiveX interfaces, and Win32 API functions are examples of Unmanaged Code. If you have coded in VB 6 or VC++, chances are you are already familiar with these unmanaged applications. In essence, unmanaged code is one that compiles directly to machine code. Unmanaged code lacks some of the key features such as Code-Access-Security or Memory management which were not available in the runtime. However, it was only accessible through the operating system through API calls provided in the Windows SDK.
The common language runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW). Although the RCW appears to be an ordinary object to .NET clients, its primary function is to marshal calls between a .NET client and a COM object.
The image below shows how COM objects can be accessed through the runtime callable wrapper.
Consuming COM from .NET:
Following are the steps to expose COM components to the .NET Framework:
- Import a type library as an assembly
- Create COM types in managed code
- Compile an interop object
- Deploy an interop application
Please note, starting with VS 2010, you can embed type information from an interop assembly directly into your executable by instructing the compiler.