The using Directive

I l @ ve RuBoard

The #using Directive

#using can be considered equivalent to the import statement and is used to refer to the .NET libraries. For example, to use some of the .NET framework classes in your C++ code, you first employ the following:

 #using <mscorlib.dll> 

This directive should be followed by the declaration for exactly which namespaces you need.

Listing 1.4.1 shows the creation of a simple application containing a GC class.

Listing 1.4.1 managed.cpp : A First Look at Garbage Collected C++
 #using <mscorlib.dll> // import the library using namespace System; __gc class MCPPDemo { public:     void SayHello()     {         Console::WriteLine("Hello Managed C++");     } }; void main() {     MCPPDemo *pD=new MCPPDemo;     pD->SayHello(); } 

There are a few things in this code that need explanation. First of all, there is a distinct difference between #using and using namespace . The #using directive refers to a DLL that will be imported. The using namespace maintains its classic meaning. Next, the main function creates a pointer and assigns a new class to it, uses it, and then exits without deleting. This, surprisingly, is correct because the __gc keyword applied to the class defines it as being managed by the .NET runtime. The Garbage Collector concerns itself with the lifetime of such objects and will delete it for you when you stop using it. The result is no memory leaks.

Because __gc classes are specifically created on the managed heap, you cannot just create an instance on the stack as follows :

 MCCPDemo d; 

If you try this you will get an error. You must always create GC classes with the new operator and use the -> fleche when you invoke its methods or use its data. This is an odd paradox of managed C++ because C# and other managed languages use dot notation exclusively when referring to class members .

If you want to run the program in Listing 1.4.1, type it in with Notepad, save it to the file managed.cpp , and then use the following command line to compile it:

 CL /CLR managed.cpp 

It will create managed.exe , which you can run from the command line. Notice the distinct lack of an explicit link step. The linker is invoked automatically.

I l @ ve RuBoard


C# and the .NET Framework. The C++ Perspective
C# and the .NET Framework
ISBN: 067232153X
EAN: 2147483647
Year: 2001
Pages: 204

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net