Managed and Unmanaged Code

A compiler that emits unmanaged code compiles your source to machine code, which then just runs under Windows. A compiler that emits managed code does not compile your source to machine code, but rather to Intermediate Language (IL). Managed code runs in the Common Language Runtime, not directly on Windows.

When you build a managed application, your code is compiled to IL in a file called an assembly , along with metadata that describes the classes, methods , and attributes (such as security requirements) of the code you've created. This assembly is the one-stop -shopping unit of deployment in the .NET world. You copy it to another server to deploy the assembly thereand often that copying is the only step required in the deployment.

Managed code runs in the Common Language Runtime. The runtime offers a wide variety of services to your running code. In the usual course of events, it first loads and verifies the assembly to make sure the IL is OK. Then, just in time, as methods are called, the runtime arranges for them to be compiled to machine code suitable for the machine the assembly is running on, and caches this machine code to be used the next time the method is called. (This is called Just In Time, or JIT compiling, or often just jitting .)

As the assembly runs, the runtime continues to provide services such as security, memory management, threading, and the like. The application is managed by the runtime. By contrast, unmanaged code runs under Windows as it always has.

Compilers that emit unmanaged code include

  • Visual C++ 6 and earlier

  • Visual Basic 6 and earlier

  • Any C++ compiler for Windows other than Visual C++ .NET

  • Visual C++ .NET 2002 and 2003

Compilers that emit managed code include

  • Visual C# .NET 2002 and 2003

  • Visual Basic .NET 2002 and 2003

  • Other compilers for Visual Studio that meet the Common Language specification

  • Visual C++ .NET 2002 and 2003

Notice anything unusual about the two lists? Visual C++ .NET 2002 and 2003 are on both of themyou have a choice of whether you build a managed or an unmanaged application. Visual C++ .NET is the only language provided with Visual Studio .NET that can emit either managed or unmanaged code and can even combine them within a single application.

Advantages of Managed Code

Managed code is, in many ways, a huge improvement over unmanaged code. The services the runtime offers to running code include

  • Memory management

  • Security

  • Threading

  • Exceptions

  • Interoperability between languages

  • Interoperability to and from COM

  • Interoperability to old-style DLLs

Interoperability, as provided by the runtime, includes parameter marshalling, type conversions, and even translating COM HRESULTs into exceptions.

One of the astonishing things Visual C++ .NET can do is to take old C++ code, written before the .NET Framework was invented, and compile it to managed code. The classes and objects used in that code will all be unmanaged data, but the code will compile to IL and run in the runtime. If this newly managed code calls methods and functions of unmanaged DLLs or LIBs, no problem! As the C++ Dev Team says, "It Just Works"and it does.

When you build your application as managed code, you have easy access to all the .NET class libraries, to components written in Visual Basic .NET or C#, and to both managed and unmanaged C++ code. You can leverage all this code for maximum productivity, and enjoy all the latest functionality provided in the libraries.

Advantages of Unmanaged Code

Unmanaged code doesn't run in the runtime, it just runs under Windows. That means the computers on which your application are installed don't need the .NET Framework. During the first few years of .NET, you won't be able to count on every Windows machine having the framework. Starting with Windows Server 2003, every new release of Windows will include the framework, and it's also available as a Windows Update, so everyone who keeps up to date will have it. But there's a large segment of the population who never install Windows Updates or upgrade their operating systems. Code aimed at those users should be unmanaged code, or should be shipped on a CD with an install program that installs the framework automatically.

What if the code you're writing is a library of sorts, designed to be called from older unmanaged code as well as new managed code? You could write it as a .NET object and wrap it so it's exposed as a COM component. That would allow your unmanaged code to access it easily, but at a slight performance cost. Alternatively, you could write it as an unmanaged COM component or an unmanaged DLL, and let the new managed code pay the small performance cost for accessing it. Your decision will probably be based on which of the applications that need to use your code are more performance sensitive. For example, if one application is used by hundreds of clients throughout the day, whereas the other is used by one administrator a few times a week, impose the performance penalty on the administrator's application and ensure the users have the fastest experience possible. That means writing your library as managed if the user application is managed, or unmanaged if the user application is unmanaged. Either way, interoperability will be possible; it's just a matter of deciding who pays the performance penalty.

Performance Considerations

Which is faster, managed or unmanaged code? The answer is a resounding "it depends." In the simplest casecode that doesn't call out to any other codeunmanaged is usually faster. You can test this yourself by writing a simple unmanaged console application, and then writing the same main() as a managed console application. Which version runs faster depends on exactly what the code does. The runtime has more "checks and balances ," which can impose some performance penalties, and when you compile to IL you cannot take advantage of certain compiler switches that produced optimized machine code (for example, to take advantage of a particular CPU chip), so you would expect the managed code to always be slower. But once in a while, it's quicker!

Here's an examplean entire application in unmanaged C++:

 // LegacyArithmetic.cpp : Defines the entry point for the console application. // #include "stdafx.h"  #include <iostream> using namespace std; #include <atltime.h> class ArithmeticClass { public:     double Add( double num1,  double num2); }; double ArithmeticClass::Add(double num1, double num2) {     return num1+ num2; } int _tmain(void) {     ArithmeticClass arith;     double answer ;     CTime start = CTime::GetCurrentTime();     for (long i=0;i<10000000;i++)         answer = arith.Add(1.1,2.3);     CTime stop = CTime::GetCurrentTime();     CTimeSpan span = stop - start;     cout << "It took " << span.GetTotalSeconds() << " seconds"  << endl;    return 0; } 

Here's the same application as managed C++:

 // This is the main project file for VC++ application project // generated using an Application Wizard. #include "stdafx.h"  #include <tchar.h> using namespace System; class ArithmeticClass { public:         double Add( double num1,  double num2); }; double ArithmeticClass::Add(double num1, double num2) {     return num1+ num2; } // This is the entry point for this application int _tmain(void) {     double answer;     ArithmeticClass arith;     DateTime start = DateTime::get_Now();     for (long i=0;i<10000000;i++)         answer = arith.Add(4.7,3.2);     DateTime stop = DateTime::get_Now();     TimeSpan span = stop - start;     Console::Write("It took " );     Console::Write(span.TotalSeconds);     Console::WriteLine(" seconds");     return 0; } 

These applications are presented in their entirety primarily to demonstrate a way of determining how long code takes to run, and partly to show how many times you'll have to repeat a loop to get a measurable time difference. Unless you're writing some computationally expensive code, you might never see a difference between managed and unmanaged C++. However, just as a point of interest, when you run these two applications the managed code runs measurably quicker, every time. The only difference between the two applications is that the unmanaged application uses CTime (from MFC) to time itself and the managed application uses DateTime (from the System namespace) to time itself.

If your code calls out to unmanaged code, going through COM Interop or PInvoke (the only options available to VB and C# programmers) will impose a performance penalty. But calling out to that code using "It Just Works" is as fast as a direct call.

Bottom line? Your decision shouldn't be based on a prejudice about speed. If you can't count on having the framework on the target machine, write your code as unmanaged. If your code will be called from both managed and unmanaged, and the unmanaged calling code is more performance sensitive, write your code as unmanaged. Otherwise, write it as managed. When it's complete, if you have a performance issue, consider compiling portions of it as unmanaged and test to see whether that improves performance.

Microsoft Visual C++. NET 2003 Kick Start
Microsoft Visual C++ .NET 2003 Kick Start
ISBN: 0672326000
EAN: 2147483647
Year: 2002
Pages: 141
Authors: Kate Gregory © 2008-2017.
If you may any questions please contact us: