Microsoft Visual C++ .NET 2003 Kick Start

The previous chapter discussed the advantages of a layered design, and of putting functionality into a class library, whether that library is shared among several applications or used by only one. If you're building a class library, you need to consider whether it should be written in managed or unmanaged code.

At first glance, unmanaged code seems like the better choice. After all, managed C++ can call unmanaged code through It Just Works (IJW), but unmanaged code can only call managed code through .NET Interop, which is a little slow. And unmanaged code is generally faster than managed code. But the runtime offers services to your running code, including memory management, that will make your class library simpler to write and more reliable when it's running. As well, managed code can be called from any other managed language (such as Visual Basic .NET or C#), which can simplify (and speed up) multi-language application development.

The binary compatibility provided by the .NET runtime is an enormous benefit. When you develop unmanaged code in Visual Basic 5 or unmanaged C++, the applications you create can only interact through COM. This imposes a performance penalty, and the development techniques are anything but simple. You can learn more about COM in Chapter 8, "Writing COM Components in C++," and Chapter 9, "Using Existing COM Components in C++." When you develop managed code, you write none of the plumbing to enable your applications to interact; they simply interact within the runtime. What's more, the performance is far better than traditional COM applications.

When you write an unmanaged class library, using it from other code requires at least two and perhaps three steps:

  • You must tell the C++ compiler what classes and functions are in the library by including a header file (and usually you must set an option to help the compiler find the header file).

  • You must tell the C++ linker where to find the compiled code by adding the library file to the dependencies.

  • You might need to set linker options to ignore a version of the C runtime library that is brought in with the library you are using.

In contrast, a managed class library is in an assembly, a complete self-describing unit. When you add a reference to an assembly, it takes care of everything for you in a single step, as you'll see in the sample applications later in this chapter.

Категории