Calling Custom .NET DLLs from Your Managed C Code

I l @ ve RuBoard

Calling Custom .NET DLLs from Your Managed C++ Code

Managed C++ uses .NET DLLs whenever it imports runtime elements such as MSCORLIB.DLL with the #using statement. It is also useful to be able to implement a portion of your code in managed C++ and a portion in C# or VB. This means that you will have to import and use your own custom DLLs. The process is simple and is described in this section.

First we'll create a C# DLL that we can import and invoke. Listing 1.4.9 shows a very simple DLL that has one class and one method.

Listing 1.4.9 mydll.cs : A Simple C# DLL
 using System; namespace mydll { public class myclass {     public void MyMethod()     {         Console.WriteLine("MyMethod invoked!!!");     } } } 

You don't have to be a C# expert to see how this works. Note that the class is declared with the public modifier. This will allow it and its methods to be exported from the library. Enter this file with Notepad in a scratch directory, save it as mydll.cs , and compile it with the C# compiler as follows :

 csc /t:library mydll.cs 

The /t: command-line option tells the compiler to create a library DLL. You should see no errors or warnings.

This has nothing to do with the function of writing or using the DLL but just as a matter of interest, you might want to type in the following command line, too:

 Ildasm mydll.dll 

This will bring up the Intermediate Language Disassembler (ILDASM), which will enable you to examine the DLL that you've just created. Figure 1.4.1 shows this.

Figure 1.4.1. ILDASM, showing the contents of the test DLL.

graphics/0104fig01.gif

You could also use ILDASM to examine some of the other executable files we have created in this chapter.

Listing 1.4.10 shows a simple C++ class that uses the MyMethod call in the mydll namespace.

Listing 1.4.10 useCSdll.cpp : A C++ Program That Uses a Custom C# DLL
 #using <mscorlib.dll> #using <mydll.dll> using namespace System; using namespace mydll; void main(void) {     myclass *pM=new myclass();     pM->MyMethod(); } 

Enter this file using Notepad and save it as useCSdll.cpp . Notice that the #using statement and the using namespace directive both reference the C# DLL we created in Listing 1.4.9.

Compile the file with the following command:

 cl /CLR useCSdll.cpp 

Run it by typing usecsdll at the command prompt.

You will see that the C# DLL you created is loaded and 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