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:
- Open the New Project Wizard.
- Select Win32 Dynamic-Link Library.
- Name the project as DemoDll.
- In the next screen, select “A dll that exports some symbols” radio button.
- Click Finish. The dll project will be created.
- Now open the file DemoDll.cpp. You can see a function definition for “DEMODLL_API int fnDemoDll(void)”.
- Replace this function with the following code
DEMODLL_API int fnDemoDll(int a,int b)
{
return a+b;
} - Open the DemoDll.h file and insert the declaration “DEMODLL_API int fnDemoDll(int a,int b)”
- 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 - Remember to add this DemoDll.def into the project.
- 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.