新建專案 -> Console Application -> 選 DLL File
1. 在 DLL 檔裡面要先 Define 這行!
#define DLL extern "C" __declspec(dllexport)
2. 開始在 DLL 檔裡面寫 Function !!
DLL int sum(int c){ return ++c; }
--------------------------------------DLL 檔寫完了
如何呼叫 DLL 檔裡面的 Function ?
在一個MFC程式中..
HINSTANCE hinstDLL=LoadLibrary(L"theDLL.dll"); //讀取 DLL
if(hinstDLL!=0){ //如果有找到 DLL 檔
typedef int(__cdecl *Connect)(int i); //先宣告一下要連結的函式的prototype
Connect Proc; //宣告一下連結用的Connect指標 (應該是指標吧!?)
Proc = (Connect)GetProcAddress(hinstDLL,"sum"); //用Proc連結 DLL 中的函式
int get=Proc(2); //開始使用DLL中的函式,注意DLL中的函式名稱從sum變成Proc了
FreeLibrary(hinstDLL); //DLL用完沒有利用價值了,就可以扔了
CString g;
g.Format((CString)"%d",get); //這三行是顯示函式回傳的值,應該是2+1=3 才對
MessageBox(g);
}
else{ printf("找不到你的DLL檔啦!你放在哪裡!?"); }
- 12月 08 週三 201022:33
在VS 2008 底下 創建DLL檔的方式
文章標籤
全站熱搜

typedef int(__cdecl *Connect)(int i); //先宣告一下要連結的函式的prototype 1. 應該是 typedef int (__cdecl *Connect)(int i); // 第一個 int 要有空白 2. 做動態連結檔時,__cdecl 與 __stdcall 有所差異,這個太深入跳過。 3. Connect 為函式指標 (function pointer) ex: int sum(int a, int b) { return a+b;} // function int (*func)(int, int); // declare func = sum; // assign function pointer printf("%d", func(10, 20)); // will output 30 可看這裡 http://edisonshih.pixnet.net/blog/post/27692492 另外 C/C++ 裡面的 qsort function, 有一個參數就是要傳 function pointer. 所以上面的 Connect ,是被定義成,一個int引數,return int 的 func ptr. 若原本的 dll 有多個 func, 且param, return 不同,就要再定義其它 func ptr. 這篇真的寫得很好,簡單明了,認不住給個讚!