动态链接库
1.01 显式链接DLL
/* 创建dll类 */
int fnTest(void);
#include "stdafx.h"
#include "Test.h"
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
nCount++;
break;
case DLL_PROCESS_DETACH:
nCount--;
break;
default:
break;
}
return TRUE;
}
int fnTest(void)
{
return 100;
}
/* test.def */
; Test.def : Declares the module parameters for the DLL.
LIBRARY "Test"
DESCRIPTION 'Test Windows Dynamic Link Library'
EXPORTS
fnTest
/* 动态加载 */
void CDemoDlg::OnTest()
{
//加载DLL
HINSTANCE hModule = LoadLibrary(_T("test.dll"));
if (hModule == NULL)
{
AfxMessageBox(_T("test.dll加载失败\n"));
return;
}
typedef int (_cdecl *FUNTEST)(void);
FUNTEST pfnTest;
//获得导出函数的地址
pfnTest = (FUNTEST)GetProcAddress(hModule, "fnTest");
//调用导出函数
if (pfnTest != NULL)
{
/* 函数调用 */
int nValue = (*pfnTest)();
CString strMessage = _T("");
strMessage.Format(_T("%d"), nValue);
AfxMessageBox(strMessage);
}
else
{
int n = GetLastError();
TRACE(_T("LastError:%d\n"), n);
}
//释放DLL
FreeLibrary(hModule);
}
1.02 显式链接DLL
//DLL导出函数的头文件
#include "Test.h"
//DLL的导入库lib文件
#pragma comment(lib, "test.lib")
void CDemoDlg::OnTest()
{
//直接调用DLL的导出函数
int nValue = fnTest();
}