1、DLL源代碼
MyDll.h
//////////////////////////////////////////////////////////////////////////
// MyDll.h
// 聲明函數
int _stdcall Add(int a,int b);
int _stdcall Sub(int a,int b);
//////////////////////////////////////////////////////////////////////////
// MyDll.h
// 聲明函數
int _stdcall Add(int a,int b);
int _stdcall Sub(int a,int b);
MyDll.cpp
// MyDll.pp
// 聲明實作
#include "MyDll.h"
int _stdcall Add(int a,int b)
{
return a+b;
}
int _stdcall Sub(int a,int b)
return a-b;
// MyDll.pp
// 聲明實作
#include "MyDll.h"
int _stdcall Add(int a,int b)
{
return a+b;
}
int _stdcall Sub(int a,int b)
return a-b;
MyDll.def
; MyDll為工程名
LIBRARY MyDll
; 在這裡聲明需要導出的函數
EXPORTS
Add
Sub
; MyDll為工程名
LIBRARY MyDll
; 在這裡聲明需要導出的函數
EXPORTS
Add
Sub
2、Exe測試代碼
示範動态與靜态加載的方法,看代碼吧!
void CTestDlg::OnBtnStatic()
// TODO: Add your control notification handler code here
// 靜态加載的方法:
// 1、添加頭檔案 #include "MyDll.h"
// 2、引入Lib庫 #pragma comment(lib,"MyDll.lib")
// 3、這樣就可以直接使用MyDll.h中導入的函數
CString str;
str.Format("靜态加載: 1+1=%d 1-1=%d",Add(1,1),Sub(1,1));
MessageBox(str);
void CTestDlg::OnBtnDynamic()
// 動态加載的方法:
// 不需要引入頭檔案與lib檔案,僅需要一個dll即可
// 注意這裡的條約調用約定_stdcall不要忘記加(不然會引會esp出錯)
typedef int (_stdcall *ADDPROC)(int,int);
typedef int (_stdcall *SUBPROC)(int,int);
HINSTANCE handle;
handle = LoadLibrary("MyDll.dll");
if(handle)
{
// GetProcAddress第二個參數有兩種方法:
// 1、通過DLL中的函數名
// 2、通過Depend工具中Ordinal索引值來檢視
ADDPROC MyAdd = (ADDPROC)GetProcAddress(handle,"Add");
SUBPROC MySub = (ADDPROC)GetProcAddress(handle,MAKEINTRESOURCE(2));
if( !MyAdd )
{
MessageBox("函數Add位址擷取失敗!");
return;
}
if( !MySub )
MessageBox("函數Sub位址擷取失敗!");
CString str;
str.Format("動态加載: 1+1=%d 1-1=%d",MyAdd(1,1),MySub(1,1));
MessageBox(str);
}
FreeLibrary(handle);