Wednesday, February 07, 2007

Managed and Unmanaged Code


Recently I was talking to a young programmer and the topic of managed versus unmanaged code came up. The programmer did not know what the difference between the two. It took me a few seconds to process what he just said before beginning to enter into an explanation of the difference. The young programmer was having difficulty in understanding what I was saying and kept insisting that he knew many languages (Javascript and VB.Net) and has never heard of this.

The discussion led me to wonder how many other programmers do not know the difference. I then decided that the best thing to do was to write a short overview of the differences. This is not a complete description of all difference, but more of a general overview to help those that might not know the difference.

What is Managed Code?

Managed Code is what the Visual Studio 2005 compiler languages VB.Net and C# create. This code is then compiled into an Intermediate Language (IL), which is subsequently run n the Common Language Runtime (CLR). The CLR can handle code that is written in VB.Net, C#, or J#. It accomplishes this because each of those languages compiles down to IL.

The CLR will verify and load the IL, and if it is okay run it. Then the code is compiled to machine code just in time when the methods are called. This method of using a JIT compiler is similar to what is implemented in Sun’s Java. The JIT compiling allows memory, security, and threading to be managed at runtime.

What is Unmanaged Code?

Unmanaged code is that it will compile directly to machine code. There will not be any intermediate steps, and will compile directly to machine code. The compiled application will not have any of its resources managed for it, and will depend upon the operating system to provide them.

As an example, if the application requires memory it must dynamically ask for more from the operating system explicitly. Any programmer who has written in C++ knows that memory leaks can be a major source of bugs in their code. The programmer is responsible for management the memory that his program uses, or does not use.

Microsoft Visual C++ is a very powerful tool which allows the programmer the ability to write in both managed and unmanaged code. Visual C++ provides the ability to chose a CLR application which is managed, or a ATL, MFC, Win32 project for unmanaged applications. The benefits and power of being to write both managed and unmanaged code are immense and quickly apparent for the experienced programmer, while not so for the inexperienced programmer..

Labels: