Managed, Unmanaged,Native

Managed, Unmanaged,Native: What Kind of Code Is This?

With the release ofVisual Studio .NET 2003 (formerly known as Everett) on April 24th,many developers are now willing to consider using the new technology known asmanaged code. But especially for C++ developers, it can be a bit confusing.That's because C++, as I pointed out in my first column here, is special.

What Is Managed Code?

Managed Code is whatVisual Basic .NET and C# compilers create. It compiles to Intermediate Language(IL), not to machine code that could run directly on your computer. The IL iskept in a file called an assembly, along with metadata that describes theclasses, methods, and attributes (such as security requirements) of the code you'vecreated. This assembly is the one-stop-shopping unit of deployment in the .NETworld. You copy it to another server to deploy the assembly there—and oftenthat copying is the only step required in the deployment.

Managed code runs in theCommon Language Runtime. The runtime offers a wide variety of services to yourrunning code. In the usual course of events, it first loads and verifies theassembly to make sure the IL is okay. Then, just in time, as methods arecalled, the runtime arranges for them to be compiled to machine code suitablefor the machine the assembly is running on, and caches this machine code to beused the next time the method is called. (This is called Just In Time, or JITcompiling, or often just Jitting.)

As the assembly runs, theruntime continues to provide services such as security, memory management,threading, and the like. The application is managed by theruntime.

Visual Basic .NET and C#can produce only managed code. If you're working with those applications, youare making managed code. Visual C++ .NET can produce managed code if you like:When you create a project, select one of the application types whose namestarts with .Managed., such as .Managed C++ application..

What Is Unmanaged Code?

Unmanaged code is whatyou use to make before Visual Studio .NET 2002 was released. Visual Basic 6,Visual C++ 6, heck, even that 15-year old C compiler you may still have kickingaround on your hard drive all produced unmanaged code. It compiled directly tomachine code that ran on the machine where you compiled it—and on othermachines as long as they had the same chip, or nearly the same. It didn't getservices such as security or memory management from an invisible runtime; itgot them from the operating system. And importantly, it got them from theoperating system explicitly, by asking for them, usually by calling an APIprovided in the Windows SDK. More recent unmanaged applications got operatingsystem services through COM calls.

Unlike the other Microsoftlanguages in Visual Studio, Visual C++ can create unmanaged applications. Whenyou create a project and select an application type whose name starts with MFC,ATL, or Win32, you're creating an unmanaged application.

This can lead to someconfusion: When you create a .Managed C++ application., the build product is anassembly of IL with an .exe extension. When you create an MFC application, thebuild product is a Windows executable file of native code, also with an .exeextension. The internal layout of the two files is utterly different. You canuse the Intermediate Language Disassembler, ildasm, to look inside an assemblyand see the metadata and IL. Try pointing ildasm at an unmanaged exe and you'llbe told it has no valid CLR (Common Language Runtime) header and can't bedisassembled—Same extension, completely different files.

What about Native Code?

The phrase native codeis used in two contexts. Many people use it as a synonym for unmanaged code:code built with an older tool, or deliberately chosen in Visual C++, that doesnot run in the runtime, but instead runs natively on the machine. This might bea complete application, or it might be a COM component or DLL that is beingcalled from managed code using COM Interop or PInvoke, two powerful tools thatmake sure you can use your old code when you move to the new world. I prefer tosay .unmanaged code. for this meaning, because it emphasizes that the code doesnot get the services of the runtime. For example, Code Access Security inmanaged code prevents code loaded from another server from performing certaindestructive actions. If your application calls out to unmanaged code loadedfrom another server, you won't get that protection.

The other use of thephrase native code is to describe the output of the JIT compiler, the machinecode that actually runs in the runtime. It's managed, but it's not IL, it'smachine code. As a result, don't just assume that native = unmanaged.

Does Managed Code Mean Managed Data?

Again with Visual Basicand C#, life is simple because you get no choice. When you declare a class inthose languages, instances of it are created on the managed heap, and thegarbage collector takes care of lifetime issues. But in Visual C++, you get achoice. Even when you're creating a managed application, you decide class byclass whether it's a managed type or an unmanaged type. This is an unmanagedtype:

classFoo

{

private:

   int x;

public:

    Foo(): x(0){}

    Foo(int xx): x(xx) {}

};

This is a managed type:

__gcclass Bar

{

private:

   int x;

public:

    Bar(): x(0){}

    Bar(int xx): x(xx) {}

};

The only difference isthe __gc keyword on the definition of Bar. But it makes a huge difference.

Managed types aregarbage collected. They must be created with new, never on the stack. So thisline is fine:

Foof;

But this line is notallowed:

Barb;

If I do create aninstance of Foo on the heap, I must remember to clean it up:

Foo*pf = new Foo(2);

//. . .

deletepf;

The C++ compileractually uses two heaps, a managed an unmanaged one, and uses operatoroverloading on new to decide where to allocate memory when you create aninstance with new.

If I create an instanceof Bar on the heap, I can ignore it. The garbage collector will clean it upsome after it becomes clear that no one is using it (no more pointers to it arein scope).

There are restrictionson managed types: They can't use multiple inheritance or inherit from unmanagedtypes, they can't allow private access with the friend keyword, and they can'timplement a copy constructor, to name a few. So, you might not want yourclasses to be managed classes. But that doesn't mean you don't want your codeto be managed code. In Visual C++, you get the choice.

What's Next?

Well, keep reading. Ifyou look through the index of previous columns, you'll see I cover bothmanaged and unmanaged topics. I especially like to show how to do the samething in both worlds. It can be frustrating to have so much choice, but alltold I prefer it to the alternative. In future columns, I'll explore the worldof interoperability a little more, because I strongly believe that's a strengthC++ programmers will be bringing to projects for a long time to come.

About the Author

Kate Gregory is a founding partner of GregoryConsulting Limited (www.gregcons.com). In January 2002, she wasappointed MSDN Regional Director for Toronto, Canada. Her experience with C++stretches back to before Visual C++ existed. She is a well-known speaker andlecturer at colleges and Microsoft events on subjects such as .NET, VisualStudio, XML, UML, C++, Java, and the Internet. Kate and her colleagues atGregory Consulting specialize in combining software develoment with Web sitedevelopment to create active sites. They build quality custom and off-the-shelfsoftware components for Web pages and other applications. Kate is the author ofnumerous books for Que, including Special Edition Using Visual C++ .NET.

 


你可能感兴趣的:(Managed, Unmanaged,Native)