Assembly Referencing


Once you place all of your library logic in an assembly, you are going to want to access it. With Managed C++, getting access to or referencing an assembly is remarkably easy: one file copy (even this step can be eliminated) and one line of code. In fact, the command to compile the application doesn't even change.

After you have done these two things, you can access the library classes as if they were coded directly within your application. If you are using Visual Studio .NET, then you will even have full access to the type definitions within the assembly using IntelliSense.

You'll learn more about configuring access to library assemblies in Chapter 17, but the simplest method is just to place the assembly in the same directory where the final .exe file is going to be placed. Moving or copying the assembly can be done by using the simple copy.exe command or by just dragging and dropping using Windows Explorer. That's it. There's no registering, unregistering, GUIDs, or variants.

You've already covered the line that needs to be added to the source code: #using. Simply add a #using statement at the top of the source code, and voila! The library is available as if it were coded right there in your code. You don't even need any header files—the assembly fully describes itself to the compiler so that it doesn't need any headers.

Listing 4-10 shows an application called PlayCards that references the Cards.dll assembly that you created (in two ways) earlier. Notice that you have access to the namespace and classes, just like you would if you had coded them in the application. You can make references and pointers to the classes. In fact, you can even inherit from them. Basically, you can use them just as you do any other class in the application.

Listing 4-10: PlayCards.cpp: Reference a User Assembly

start example
 #using <mscorlib.dll> #using <cards.dll> using namespace System; using namespace Cards; Int32 main(void) {     Deck &deck = *new Deck;     deck.Shuffle();     Card *card;     Int32 cnt = 0;     while ((card = deck.Deal()) != 0)     {         Console::Write(card->ToString());         Console::Write("\t");         cnt++;         if (cnt > 4)         {             Console::WriteLine("");             cnt = 0;         }     }     Console::WriteLine("");     return 0; } 
end example

To build this application from the command line, simply copy Cards.dll to the same directory as the source of PlayCards.cpp and then execute the same command from the command line as you always have:

 cl PlayCards.cpp /CLR 

Figure 4-1 shows a sample output of this random program.

click to expand
Figure 4-1: Example results of PlayCards.exe




Managed C++ and. NET Development
Managed C++ and .NET Development: Visual Studio .NET 2003 Edition
ISBN: 1590590333
EAN: 2147483647
Year: 2005
Pages: 169

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