Introduction
In my previous article, I mentioned simply DLL creation and using it. But it exports function only. Now, I want to describe "how to export classes from a DLL?"
How to build MFC DLL Containing New Class?
- Run VC++.
- Choose : File > New.
- Create "MFC AppWizard (DLL)" (named e.g.: MyScndDll).
- Click right mouse button on root branch in "ClassView", point and click "New Class...".
- Select Generic Class as class type, and name it e.g. CRectArea.
- Declare in top of file of "RectArea.h":
#define DLLEXPORT __declspec(dllexport)
__declspec(dllexport)
's purpose is to add the "export directive" to the object file so you don't need a .DEF file. To make code more readable, define a macro for __declspec(dllexport)
: DLLEXPORT
.
- Now, for exporting per class that you want, type before its declaration: "
DLLEXPORT
" like this: class DLLEXPORT CRectArea
{
public:
CRectArea();
virtual ~CRectArea();
};
- Now, declare a member function for newly created class. E.g.,
Calculate
: class DLLEXPORT CRectArea
{
public:
int Calculate(int ParOne,int ParTwo);
CRectArea();
virtual ~CRectArea();
};
- and define it:
int CRectArea::Calculate(int ParOne,int ParTwo)
{
return ParOne*ParTwo;
}
- Press Build button.
- Bring out DLL from oven!!
Note: linker also builds an "import library" with same DLL name but .lib extension.
How to use MFC DLL?
- Run VC++.
- Choose : File > New.
- Create "MFC AppWizard (exe)".
- Choose "Dialog based", then click Finish.
- Choose: Project > Add To Project > New > C/C++ Header File.
- Name file, e.g.: Imports.
- Declare in Imports.h:
#define DLLIMPORT __declspec(dllimport)
__declspec(dllimport)
's purpose is to add the "import directive" to the object file. To make code more readable, define a macro for __declspec(dllimport)
: DLLIMPORT
.
- Type after it, declaration of exported function from DLL. Note: we must type "
DLLIMPORT
" whenever intending to import class: class DLLIMPORT CRectArea
{
public:
int Calculate(int ParOne,int ParTwo);
CRectArea();
virtual ~CRectArea();
};
This is the same class that you declared and defined in the DLL. Here, have introduce as "import class". But it is unrecognized for current project and we must resolve it for linker.
- Copy .lib file from release or debug folder (depending on current project setting) in previous project to current directory project because it must link with EXE. Inside .lib file (same import library), exist information about exported class from DLL.
- Back to VC++ environment and choose: Project > Settings > Link (tab).
- Type [.lib file previous project] in "Object/library modules:"
For example: MyScndDll.lib, then press OK. It will resolve externals. Here: CRectArea
class.
- Cause we intend to use function in ...Dlg.cpp file (e.g.: ImportClassDlg.cpp), type in top of file:
#include "Imports.h"
- Now, you can use function of exported class, like this:
void CImportClassDlg::OnCalc()
{
UpdateData();
m_Result=m_RectArea.Calculate(m_ParOne,m_ParTwo);
UpdateData(FALSE);
}