Friday, May 22, 2009

Dll creation

creation of win32 dll

step 1:
create a win32 project with the name Sampledll

step 2:
A Sampledll.cpp file will be created with Dllmain function
BOOL APIENTRY DllMain(HMODULE hModule,DWORD reason_for_call,LPVOID lpReserved )
{
return TRUE;
}

step 3:
create a .h file named Sampledll.h and expotable APIs and callback function

#ifdef VISUALIMITSINTERFACE_EXPORTS // in the project settings,c++ ->preprocessor we can find this macro
#define MY_DLL DLLEXPORT
#else
#define MY_DLL DLLIMPORT
#endif

typedef void (*fun2)(int, int);
extern "C" MY_DLL int fun1( int a , int b);
extern "C" MY_DLL int fun3(char* sz1,fun2 fpfun2);

step 4:

In the Sampledll.cpp , write exportable function defintions
extern "C" DLLEXPORT int fun1( int a , int b){... ..return n;}
extern "C" DLLEXPORT int fun3(char* sz1,fun2 fpfun2){....fpfun2(i,n); // callback function that used to call a function in Exe
}

step 5:
create a Exe application

Include the file Sampledll.h

Instead of .. extern "C" MY_DLL int fun1( int a , int b);
, we can add the following lines
typedef void (*pfnfun2)(int, int); // callback function
typedef int (*pfnfun1)(char* ,char* );typedef int (*pfnfun3)(char*,pfnfun2);

step 6:

In the SampleDlg.h file declare this

pfnfun1 fun1;
pfnfun3 fun3;

step 7:

In the SampleDlg.cpp file add this callback function

void SampleCallBack(int n, int y)
{
return;
}

In a function call this API to set callback function for the dll

void CVisuaLimitsServerDlg::OnBnClickedBtnTransfer()
{
fun3(szResult,&SampleCallBack);
}

Using Loadlibrary we can load the dll

m_hInstance = LoadLibrary(L"Sampledll.dll");

if (m_hInstance)
{
fun1 = (pfnfun1) GetProcAddress (m_hInstance, "fun1");
fun3 = (pfnfun3) GetProcAddress (m_hInstance, "fun3");
}

No comments: