參考鏈接:
1.使用 VC6.0 生成 DLL
新建項目 “Win32 Dynamic-Link Library”,輸入項目名稱,確定後選擇 “A simple DLL project” 點擊“完成”。
以下爲cpp文件自動生成的代碼:
#include "stdafx.h"
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}
編輯cpp文件:
在#include "stdafx.h"的下一行加入
extern "C" __declspec(dllexport) int fun(int a, int b);
/*
這是C格式導出函數;
這種寫法一般用在C++寫的DLL中,指按C的規則導出這個函數,否則導出的函數會很怪;
加上 extern "C" 表示按標準C格式導出函數.如果去掉僅兼容C++;
其中 int fun(int a, int b) 這部分代碼是我們想用 dll 實現的函數原型聲明
如果還想加入其他的可以繼續加入 extern "C" __declspec(dllexport) int fun1(int a, int b);
*/
DllMain 是 DLL 的默認入口函數,類似於C語言的main函數,該例子無需修改此處,在 DllMain 的後面加入:
int fun(int a,int b)
{
return a+b;
}
這就是我們想用 DLL 實現的函數的定義,build 之後就會在 debug 目錄下生成我們想要的 dll 文件
2.調用 DLL
新建一個 Win32 Console Application 工程,把剛纔生成的 dll 文件拷貝到工程的根目錄下
在 stdafx.h 文件中加入:#include <windows.h>
編輯cpp文件:
#include "stdafx.h"
typedef int (*PFUN)(int,int);
void main()
{
HMODULE hModule = ::LoadLibrary("dlltest.dll");
PFUN newfun = (PFUN)::GetProcAddress(hModule,"fun");
int i = newfun(1,2);
printf("The result is %d\n",i);
::FreeLibrary(hModule);
}
然後,運行就可以看到結果了
函數接口:
typedef void (*lpFun)(void);
HINSTANCE hDll;
hDll = LoadLibrary("RegularDll.dll");
if (NULL==hDll) {
MessageBox("Dll load failed!");
}
lpFun pShowDlg = (lpFun)GetProcAddress(hDll,"ShowDlg");
if (NULL == pShowDlg) {
MessageBox("Load function \"ShowDlg\" failed!");
}
pShowDlg();*/
創建Dll的工程中,函數聲明和定義時用 _stdcall 修飾,例
void _stdcall ShowDlg(void){...}
在調用dll的工程的文件中,在文件頭部聲明庫和函數,如下例
#pragma comment(lib,"RegularDll.lib")
void _stdcall ShowDlg(void);
調用時直接ShowDlg()就可以了。
以上兩種方法在VC6.0中調試成功,保證可用!
有的文章中說這樣聲明即可:
void ShowDlg(void);
但在VC6.0下會報找不到函數ShowDlg的錯誤,不知是不是我沒有設置好?
全局變量(訪問Dll文件中的全局變量)
在創建Dll的工程中,在頭文件中這樣聲明:#define _LIB_H
extern int dllGlobalVar;
#else
extern int _declspec(dllimport) dllGlobalVar;
#endif
在創建Dll的工程的cpp文件中先定義DLL_FILE,再定義該變量,如下例:
int dllGlobalVar; //define
{
switch(ul_reason_for_call) {
case DLL_PROCESS_ATTACH:
dllGlobalVar = 100; // initialization when dll attached
break;
{
return dllGlobalVar; // use the global variable
}
#pragma comment(lib,"dllTest.lib")