Wednesday, June 1, 2011

Managed Code vs Unmanaged Code

Managed code is not compiled to machine code but to an intermediate language which is interpreted and executed by some service on a machine and is therefore operating within a secure framework which handles very dangerous like memory and threads for you. In modern usage this frequently means .NET but does not have to.

In terms of .net, The code which is written using .net dlls and .net compliant languages such as C#, VB is called as Managed Code. Also we can say that, the code developed using .net framework is called as Managed Code. This code will be executed directly by CLR(Common Language Run time).

Managed code is what created using C#, VB and other .net compliant languages. Whatever the code you write, it will be converted an intermediate language after compilation. This intermediate code is called MSIL(Microsoft Intermediate Language) code. This compiled IL code will be copied to an assembly, kept ready for usage. You can't run this assembly with out the help of CLR. Because at run time CLR's JIT compilers will convert this code into Native Code, which can be executed by Operating System. You can simple drop this assembly in to any .net installed machine and start using it. The target machine's OS be anything, but it should have .net installed. So, that's why we say, .net can create portable applications.

Unmanaged code is compiled to machine code and therefore executed by the OS directly. It therefore has the ability to do damaging/powerful things Managed code does not. This is how everything used to work, so typically it's associated with old stuff like dlls

A programmer needs to write many common functions in an unmanaged code. So functions like garbage collecting, exception handling, etc have to be handled explicitly.The code, which is developed outside .NET Framework is known as unmanaged code.The code written in C/C++ etc is called as unmanaged can't be run directly by CLR. But we can write some wrapper classes to run unmanaged code in CLR. These wrapper classes are 2 types CCW (COM Callable Wrapper) and RCW (Runtime Callabale Wrapper).

COM Callable Wrapper

Runtime Callable Wrapper

For more details on the image, please refer this post.

No comments:

Post a Comment