簡介
動(dòng)態(tài)鏈接庫最大的優(yōu)勢在于可以提供給其他應(yīng)用程序共享的資源赶掖,最小化應(yīng)用程序代碼的復(fù)雜度竿裂,其中一個(gè)十分重要的功能就是dll可以導(dǎo)出封裝函數(shù)的功能许帐。導(dǎo)出函數(shù)有兩種主要方式,分別是靜態(tài)導(dǎo)入和動(dòng)態(tài)導(dǎo)入莹妒,本文主要介紹動(dòng)態(tài)導(dǎo)入功能名船。
方法解析
(1)創(chuàng)建DLL動(dòng)態(tài)鏈接庫項(xiàng)目
創(chuàng)建DLL動(dòng)態(tài)鏈接庫項(xiàng)目
(2)在DllMain函數(shù)的上方或下方創(chuàng)建一個(gè)自定義函數(shù)(樣例使用ShowMessageBox函數(shù))
// dllmain.cpp : 定義 DLL 應(yīng)用程序的入口點(diǎn)。
#include "stdafx.h"
BOOL APIENTRY DllMain(HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
int ShowMessageBox(const WCHAR* lpText, const WCHAR* lpCaption)
{
MessageBox(NULL, lpText, lpCaption, 0);
return 0;
}
(3)創(chuàng)建.def文本文件
創(chuàng)建.def文本文件
Text.def文件代碼如下:
LIBRARY DemoDLL
EXPORTS
ShowMessageBox
(4)如果是VS平臺(tái)旨怠,必須要在連接器中添加.def文件
路徑:項(xiàng)目屬性 => 鏈接器 => 輸入 => 模塊定義文件 => 輸入.def文件的文件名
(5)編譯生成dll和lib文件
編譯生成的文件圖例
(6)編寫測試程序
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <Windows.h>
using namespace std;
typedef int(*ShowMessageBox)(const WCHAR* lpText, const WCHAR* lpCaption); //聲明函數(shù)指針渠驼,告訴程序從動(dòng)態(tài)鏈接庫導(dǎo)入的地址是什么類型的函數(shù)
int main(void)
{
HMODULE hm = LoadLibrary("DemoDLL.dll"); //加載動(dòng)態(tài)鏈接庫
if (hm == NULL)
{
printf("Library Error !\n");
system("pause");
return 0;
}
ShowMessageBox SMessageBox = (ShowMessageBox)GetProcAddress(hm, "ShowMessageBox"); //查找函數(shù)地址
if (SMessageBox == NULL)
{
cout << GetLastError() << endl;
printf("GetProcAddress error \n");
system("pause");
return 0;
}
SMessageBox(L"HelloWorld", L"Tip"); //使用dll中導(dǎo)出的函數(shù)
FreeLibrary(hm);
return 0;
}
(7)執(zhí)行成功
程序運(yùn)行畫面