Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Microsoft Visual C++ .NET Professional Projects - Premier Press

.pdf
Скачиваний:
168
Добавлен:
24.05.2014
Размер:
25.78 Mб
Скачать

Project 2 Overview

Managed C++ is new to Visual C++. Using Managed C++, you can create managed applications that are aimed at exploiting the .NET Framework’s fea-

tures, such as the garbage collector and CLR. This project is designed to illus-

 

 

Y

trate programming using Managed C++. Besides Managed C++, the project

 

L

also covers some of the salient features of the .NET framework, including

GDI+, events, and delegates.

F

 

M

 

In this project, you will be creating an application named “Easytool” that is a

dummy Paint application. ThisAapplication implements all GDI features, such as drawing using pens and brushes, and setting the required font for the text, and also illustrates eventsEand delegates handling in Managed C++.

The concepts coveredTare the following:

Programming using Managed C++

Implementing GDI+ features

Implementing events and delegates

Team-Fly®

Chapter 10

Introduction to Managed Extensions

With all the hype surrounding C#, you might be wondering where this leaves Visual C++. Don’t fret, because Visual Studio.NET still supports C++. In fact, some major changes have been made to C++. There haven’t been many

changes as far as your MFC applications go; rather, most of the changes have been in the direction of adding support for the .NET platform.

It is no secret that Visual C++ is not the best language to develop applications for the .NET platform using Visual Studio.NET. That place has been taken over by C# and Visual Basic.NET. However, Visual C++ still has an important role because, so far, it is the only Visual Studio.NET language that produces native code. All others compile into the Intermediate Language (IL). Still, Visual C++ is not the language that will be used for developing the new generation of .NET applications.

Then what does VC++.NET have to offer? Well, it will act as the bridge between the .NET platform and the existing legacy C++ code. You will use this language if you intend to migrate any of your C++ applications onto the .NET platform.

To help you achieve this migration, Microsoft has added many extensions to the traditional C++ language. It has added Managed Extensions to C++ to enable you to create applications that can be executed in the CLR, which is the .NET execution engine. This version of C++ is called Managed C++ because the CLR is a managed environment. The C++ language compiler that comes with Visual Studio.NET can also compile ISO standard C++ code into an application. Traditional code, written for compilation directly into machine code, is called unmanaged code.

With Managed C++, you can migrate existing unmanaged applications into managed applications. You can also access .NET functionality from unmanaged code. In addition, you can create wrappers around your unmanaged code so that it can be accessed from applications designed for the .NET platform. In short, you can mix unmanaged and managed code for greater flexibility and code reuse.

INTRODUCTION TO MANAGED EXTENSIONS Chapter 10 303

The C++ Language in .NET

In Chapter 1, you learned about just-in-time ( JIT) compilation and how the code in IL gets compiled and executed by the .NET runtime. In addition, you have read about the garbage collector (GC) that tracks object usage and handles memory management for these objects. The C++ compiler with Visual Studio.NET enables you to create code that is compiled into IL. In addition, you can write code that is compiled into native language. You also have the flexibility to combine code that uses native code and has unmanaged data with managed code in the same source file. This means that you can use your existing C++ code in .NET applications.

NOTE

Managed Extensions for C++ is the only compiler that allows you to mix native and IL code. No other .NET compiler allows you to do this!

At this point, you may be wondering why you should stay with unmanaged code. Instead, why not have entire applications in managed code, which can be comparatively easy to develop using C# or VB.NET? The reasons for sticking with unmanaged code are as follows:

Unmanaged code is faster than managed code, because it doesn’t have the overhead of compiling the IL to native code during execution and other .NET features like garbage collection. It can also freely use various APIs and libraries, such as Win32 API, Crypto, and DirectX.

Unmanaged code allows you to migrate your code in stages so that you are not faced with the task of trying to port entire applications.

Now, let’s get started with Managed C++. I will provide the basic concepts of Managed C++ in this chapter. You will learn to create a project using Managed C++ in the forthcoming chapters.

NOTE

The terms Managed Extensions for C++ and Managed C++ are used interchangeably.

304 Project 2 CREATING AN APPLICATION USING MANAGED C++

Programming Using Managed

Extensions for C++

In this section, you will get to know the syntax of Managed Extensions for C++. As mentioned in Chapter 1, .NET programming revolves around one main feature — namespaces. This is because all .NET classes that provide the basic functionality of the framework are a part of the System namespace. Most of the basic

.NET classes form a part of this namespace, and physically, all of these classes are part of the file System.dll. There are other specialized DLL files to supplement the functionality in the System namespace, such as System.Data.dll, System.Xml.dll, and so on, which support specific functionality. (See Appendix C for more information on namespaces.)

You will need to include the .NET libraries and headers in your Managed C++ applications. Usually, you will add the following two lines at the top of your Managed Extensions for C++ source file:

#using <mscorlib.dll>;

using namespace System;

The #using directive is similar to the #import directive in C++. The preceding #using directive imports the mscorlib.dll file that contains the type information from the core library.

The using.namespace declaration makes types within the System namespace visible.

Now, consider a simple Hello World (the most obvious choice!) application that Visual Studio.NET creates when you create a new Visual C++ application using the project template Managed C++ Application.

Create a project of the type Manage C++ application. Open the <Project Name>.cpp file. It will have the following code:

#include “stdafx.h”

#using <mscorlib.dll> #include <tchar.h>

using namespace System;

INTRODUCTION TO MANAGED EXTENSIONS Chapter 10 305

// This is the entry point for this application int _tmain(void)

{

// TODO: Please replace the sample code below with your own. Console::WriteLine(S”Hello World”);

return 0;

}

The preceding is a simple console-based Hello World application.

NOTE

Although the System.dll file is not explicitly imported, it will be always linked.

Let me now display Hello World in a message box instead of on the console. To accomplish this, you need to use the MessageBox method that is part of the System::Windows::Forms namespace. This namespace provides all GUI-related classes.

#using <mscorlib.dll>

#using <System.Windows.Forms.dll>

using namespace System::Windows::Forms;

int _tmain(void)

{

MessageBox::Show(“Hello World”); return 0;

}

Now that we have finished with the mandatory Hello World application, you will next learn about the following components of a Managed Extensions for C++ application:

Classes

Interface

Properties

306Project 2 CREATING AN APPLICATION USING MANAGED C++

Exceptions

Boxing

Classes

A managed class is created with the __gc keyword, as shown in the following code snippet:

#using <mscorlib.dll> using namespace System; __gc class AClass

{

//................

};

In the preceding code, AClass is a managed class that will be subjected to garbage collection. This class AClass also will implicitly derive from the .NET root class, System::Object (because of the __gc declaration).

When a garbage-collected class is compiled, all the methods in the code will be managed, but types (classes and structs) will become managed only if the _gc and _value specifiers are used.

You can also use the managed, and unmanaged pragma declarations to control what methods are managed and unmanaged:

#pragma unmanaged

void someMethod();

A class with a _nogc declaration is an unmanaged class. Consider an example that illustrates the use of the __nogc declaration:

__nogc class Class1

{

public:

void SomeFunction()

{

}

};

If you compile the preceding code, the class Class1 will be unmanaged. But, surprisingly, the method SomeFunction will be compiled as managed code. If you

INTRODUCTION TO MANAGED EXTENSIONS Chapter 10 307

need the method to be compiled as unmanaged code, you need to use the pragma directive:

__nogc class Class1

{

public:

#pragma unmanaged void SomeFunction()

{

}

};

NOTE

A managed class has two vital features: it can only be derived from another managed type, and it supports single inheritance only. Multiple inheritance can happen only if interfaces are used.

All managed classes need to be instantiated using the new operator:

Class1 obj1;//will generate an error.

Class *ptObj1=new Class1(); //way to do

Next, let me introduce you to abstract and sealed classes in Managed Extensions for C++.

Abstract Classes

To create an abstract class in Managed Extensions for C++, you use the __abstract keyword. The __abstract keyword prevents a class from being instantiated. In other words, this keyword creates pure virtual functions that are created only for inheritance purposes. A sample code snippet follows:

__abstract __gc class Class2

{

public:

virtual void SomeMethod() = 0;

};

308 Project 2 CREATING AN APPLICATION USING MANAGED C++

Sealed Classes

The reverse of an abstract class is a sealed class that is created using the _sealed keyword. A sealed declaration implies that the corresponding class cannot be derived from. When applied to a method in a class, this property prevents derived classes from overriding the method. Consider the following code snippet, which illustrates this point:

__gc class Class2

{

public:

__sealed SomeMethod()

{

//…

}

};

Interfaces

Interfaces in Managed C++ are similar to traditional abstract base classes. The following are some key rules governing the creation of interfaces:

The interfaces cannot contain data or static members

The interfaces cannot implement a method

The interfaces cannot have any private members

If derived, can do so only from managed interfaces or from the Sys-

tem::Object class

The interfaces cannot be declared as sealed since by its very nature an interface has to be derived by classes which implement the methods declared in the interface.

You use the __interface keyword to declare an interface. The following code declares a managed interface:

__gc __interface ICar

{

void Drive(); void Start(); };

__property

INTRODUCTION TO MANAGED EXTENSIONS Chapter 10 309

Properties

A property is a method of a class that aids in exposing data. You will look at how to add the same feature to your Managed Extensions for C++ classes.

In Managed Extensions for C++, you use the __property keyword to define a property. The following code snippet illustrates the use of the keyword:

public __gc class Class1

{

private:

String* m_someProperty; public:

__property String* get_SomeProperty()

{

return m_something;

}

__property void set_SomeProperty(String* someProperty)

{

m_someProperty = someProperty;

}

//..

};

Exceptions

Exceptions in Managed Extensions for C++ are handled the same way they were handled in C++, as the following code snippet shows:

try

{

int temp = 100 / 0;

}

catch(System::DivideByZeroException*e)

{

Console::WriteLine(e->ToString());

}

__finally

{