- Create a MFC Appwizard(exe) the project name "TestDLL"
- Using the wizard select dialog based application.
- Add three "Edit Box" and add member name as m_edA, m_edB and m_edResult and choose Category as variable and Type as int.
- Add a new class with class name "CWrapper" with class type "Generic Class".
- Add a new header file with name "MyAPI.H".
- Edit the following files as the instruction given below.
- copy the "MyDll.dll" DLL created earlier and paste it where your exe application created. By default in "Debug" folder of your Project.
// Add the following lines in MyAPI.H
#define DLLNAME "MyDLL.dll"
//function pointers for Exportable API's
typedef int (*egAddFn) (int A, int B);
// Add the following lines in TestDLLDlg.h
#include "Wrapper.h"
class CTestDLLDlg : public CDialog
{
private:
CWrapper m_Wrapper; //add this line
};
//Add the following lines in Wrapper.h
#include "MyAPI.h"
class CWrapper
{
public:
OnInitialize(); //add this line
OnUnInitialize(); //add this line
HINSTANCE m_hInstance; //add this line
int egAdd(int a,int b); //add this line
egAddFn m_egAddFn; //add this line
};
//Add the following lines in TestDLLDlg.cpp
void CTestDLLDlg::OnBtnAdd()
{
UpdateData(TRUE);
int a=0,b=0,c=0;
a=m_edA; //name of the edit box with type int
b=m_edB; //name of the edit box with type int
if(m_Wrapper.m_egAddFn)
{
c=m_Wrapper.m_egAddFn(a,b);
}
m_edResult=c; //name of the edit box with type int
UpdateData(FALSE);
}
//Add the following lines in Wrapper.cpp:
#include "Wrapper.h"
CWrapper::CWrapper()
{
m_hInstance = NULL;
//Initialize all function pointers to NULL
m_egAddFn = NULL;
OnInitialize();
}
CWrapper::~CWrapper()
{
OnUnInitialize();
}
int CWrapper::OnInitialize()
{
CString csDllPath,csLeft;
TCHAR szPath[MAX_PATH];
int nPos;
szPath[0] = NULL;
GetModuleFileName(NULL,szPath,MAX_PATH);
csDllPath = szPath;
nPos = csDllPath.ReverseFind ('\\');
if(nPos != -1)
{
csLeft = csDllPath.Left (nPos);
csDllPath.Format ("%s\\%s",csLeft,DLLNAME);
}
else
{
csDllPath = DLLNAME;
}
m_hInstance = LoadLibrary(csDllPath);
if(m_hInstance)
{
m_egAddFn = (egAddFn) GetProcAddress (m_hInstance, "egAdd");
}
else
{
m_egAddFn = NULL;
return 0;
}
return 1;
}
int CWrapper::OnUnInitialize()
{
if(m_hInstance)
{
FreeLibrary(m_hInstance);
}
else
{
m_hInstance = NULL;
//Initialize all function pointers to NULL
m_egAddFn=NULL;
return 0;
}
return 1;
}
int CWrapper::egAdd(int a ,int b)
{
if (m_egAddFn)
{
return m_egAddFn (a,b);
}
return 0;
}
No comments:
Post a Comment