Tuesday, May 5, 2009

Windows DLL Programming

Creating a DLL is very simple, There are two files you need to create. The first is a DEF (define) file. The second is the CPP (C++ source) file. Add these lines in the CPP file of the DLL.

extern
"C" __declspec(dllexport) double AddNumbers(double a, double b)
{
return a + b;
}

and in the DEF file, add the following lines, in the EXPORT section. If more than one functions are there continue the numbering, (this is optional as we have already used __declspec(dllexport), but better to add here too.)

AddNumbers @1

Once the DLL is compiled it will create .lib, and .dll files in the debug folder, we need to add the .lib to the project in which we want to use that DLL, else we will get linking error. Once the linking is done, this .lib is not needed anymore, but we need to have the DLL in the same folder as that of our EXE, else the application wont be able to find the DLL, and will fail to load.

When we use a function from the DLL, the .lib file of that DLL need to be added to the project, and also the function need to be declared as extern as shown below.

extern __declspec(dllimport) double
AddNumbers(double a, double b);