Win32 dll Creation and usage

Dll is convenient in many ways. If there are some functionalities which are expected to change over time, a Dll becomes the choice of use whether its a VB or MFC or WIN32 dll (provided the function signatures don’t change). The win32 dll is loaded by using the LoadLibrary function and the functions can be called after getting its address using GetProcAddress.

This code demo uses Windows 2000, VC++ 6.0 environment.

Creating a Win32 dll:

  1. Open the New Project Wizard.
  2. Select Win32 Dynamic-Link Library.
  3. Name the project as DemoDll.
  4. In the next screen, select “A dll that exports some symbols” radio button.
  5. Click Finish. The dll project will be created.
  6. Now open the file DemoDll.cpp. You can see a function definition for “DEMODLL_API int fnDemoDll(void)”.
  7. Replace this function with the following code
    DEMODLL_API int fnDemoDll(int a,int b)
    {
    return a+b;
    }
  8. Open the DemoDll.h file and insert the declaration “DEMODLL_API int fnDemoDll(int a,int b)”
  9. Create a new file named “DemoDll.Def” and add the following code in that file.
    ; DemoDll.def : Declares the module parameters for the DLL.
    LIBRARY “DemoDll”
    DESCRIPTION ‘DemoDll Windows Dynamic Link Library’EXPORTS
    ; Explicit exports can go here
    fnDemoDll PRIVATE
  10. Remember to add this DemoDll.def into the project.
  11. Build the project.The dll will be created.

Using the Dll:

This part explains only the dynamic loading using loadlibrary. The following sample code has to be used in a new console application.

#include <Windows.h>
#include <iostream.h>

typedef int (*ADDITIONFUNCTION)(int a,int b);
ADDITIONFUNCTION addFunction;

void main()
{
HINSTANCE hDll;
hDll = LoadLibrary("Pathofdll");
if(hDll == NULL)
{
cout<<"Error loading win32 dll"<<endl;
return ;
}
addFunction = (ADDITIONFUNCTION)GetProcAddress(hDll,"fnDemoDll");
int result;
if(addFunction != NULL)
cout<<(addFunction)(10,11)<<endl;
else
{
cout<<"error:"<<GetLastError()<<endl;
}
}

Note: Usual problems faced while doing the above will be, not creating the .def file with the required function export definitions. So, remember to create the .def file and add it to the project.