What is Managed and Unmanaged Code?

Managed Code:

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:

  1. Objects are self-describing
  2. Provides Code-Access-Security
  3. Assembly based deployment to avoid DDL hell
  4. Code development made easy
  5. Side-by-side versioning of reusable components
  6. Automatic Object Lifetime Management
  7. Seamless integration between CLR compliant languages

Unmanaged Code:

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.

Interoperability:

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.

Resources:

MSDN

Microsoft Docs

 

 

About Obi Oberoi

I am Technology Aficionado who has a passion for learning, speaking, blogging and hanging out with geeks and like minded people!
This entry was posted in .NET. Bookmark the permalink.