在网上找了好多制作动态库的资料都是关于函数动态库的方法,很少关于类动态库资料。今天拿到老大的程序,认真研究了一下,发现他是基于抽象类的方法,在dll类里面声明一个继承类并给实例化,在调用的时候需要一个动态库和一个基类文件。
l 具体生成类DLL方法:
1. 建立一个基于win32的空DLL工程
2. 添加基类头文件(BaseClass.h)
#pragma once
class BaseClass
{
public:
virtual int _stdcall Add(const int firstData, const int secondData) = 0;
virtual int _stdcall Mul(const int firstData, const int secondData) = 0;
};
extern "C" BaseClass *_stdcall InitBaseClass();//封装派生类用的函数
3. 添加派生类的头文件(InheritClass.h)
#include "BaseClass.h"
class InheritClass:public BaseClass
{
public:
InheritClass();
~InheritClass();
int _stdcall Add(const int firstData, const int secondData);
int _stdcall Mul(const int firstData, const int secondData);
};
4. 添加派生类的函数文件(InheritClass.cpp)
#include "BaseClass.h"
#include "InheritClass.h"
#include <stdio.h>
#include <stdlib.h>
BaseClass *_stdcall InitBaseClass()
{
return new InheritClass;
}
InheritClass::InheritClass()
{
}
InheritClass::~InheritClass()
{
delete this;
}
int InheritClass::Add(const int firstData, const int secondData)
{
return firstData + secondData;
}
int InheritClass::Mul(const int firstData, const int secondData)
{
return firstData * secondData;
}
5. 添加模块文件(MakeDll.def)
LIBRARY "MakeDll"
EXPORTS
InitBaseClass @1 NONAME
上面每句话的具体作用参考:
http://blog.csdn.net/zhenxiaohui/archive/2010/06/09/5659342.aspx
6. 点击运行生成MakeDll.dll和MakeDll.lib
l 动态库测试
1. 建一个基于对话框的工程,并添加四个按键(链接动态库、测试加法、测试减法和断开连接)和两个编辑框(显示加法结果和减法结果)
2. 添加代码:
TestDllDlg.h文件:
声明公共类型:
HMODULE m_hMakeDll;
BaseClass *m_pBaseClass;
int m_iFirstData;
int m_iSecondData;
typedef BaseClass *_stdcall InitBaseClass();
TestDllDlg.cpp文件:
void CTestDllDlg::OnBnClickedBtestlink()
{
m_hMakeDll = LoadLibrary("MakeDll.dll");
if (m_hMakeDll == NULL)
{
MessageBox(_T("连接动态库失败!"));
}
else
{
MessageBox(_T("连接动态库成功!"));
}
InitBaseClass * fun = (InitBaseClass *)GetProcAddress(m_hMakeDll,(LPCSTR)1);
if (fun)
{
m_pBaseClass = fun();
}
m_iFirstData = 20;
m_iSecondData = 30;
}
void CTestDllDlg::OnBnClickedCancel()
{
if (m_hMakeDll != NULL)
{
FreeLibrary(m_hMakeDll);
}
OnCancel();
}
void CTestDllDlg::OnBnClickedBtestadd()
{
int tempData = m_pBaseClass->Add(m_iFirstData,m_iSecondData);
CString str;
str.Format("%d",tempData);
GetDlgItem(IDC_EADD)->SetWindowTextA(str);
}
void CTestDllDlg::OnBnClickedBtestmul()
{
int tempData = m_pBaseClass->Mul(m_iFirstData,m_iSecondData);
CString str;
str.Format("%d",tempData);
GetDlgItem(IDC_EMUL)->SetWindowTextA(str);
}
void CTestDllDlg::OnBnClickedBtestdling()
{
if (m_hMakeDll)
{
FreeLibrary(m_hMakeDll);
MessageBox(_T("断开成功!"));
}
}
l 测试结果