[問題] DLL的製作及使用

看板C_and_CPP作者 (豆腐)時間15年前 (2009/07/30 16:38), 編輯推噓0(003)
留言3則, 2人參與, 最新討論串1/1
大家好,今天我參考了一些網路文章及MSDN,想練習DLL的製作及使用,但是出了一些 問題,想請教一下大家: 我先使用Code::Block開啟一個Dynamic Link Library Project,它會產生一段程式碼 ,我依造上面的提示再填入想新增的函式: [main.h] #ifndef __MAIN_H__ #define __MAIN_H__ #include <windows.h> #include "iostream" using namespace std; /* To use this exported function of dll, include this header * in your project. */ #ifdef BUILD_DLL #define DLL_EXPORT __declspec(dllexport) #else #define DLL_EXPORT __declspec(dllimport) #endif #ifdef __cplusplus extern "C" { #endif void DLL_EXPORT SomeFunction(const LPCSTR sometext); int DLL_EXPORT HelloWorld(); // 我增加的部份 #ifdef __cplusplus } #endif #endif // __MAIN_H__ //---------------------------------------------------------------------------- [main.cpp] #include "main.h" // a sample exported function void DLL_EXPORT SomeFunction(const LPCSTR sometext) { MessageBoxA(0, sometext, "DLL Message", MB_OK | MB_ICONINFORMATION); } int HelloWorld() // 我增加的部份 { // 我增加的部份 cout<<"Hello World"<<endl; // 我增加的部份 return 0; // 我增加的部份 } // 我增加的部份 BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { switch (fdwReason) { case DLL_PROCESS_ATTACH: // attach to process // return FALSE to fail DLL load break; case DLL_PROCESS_DETACH: // detach from process break; case DLL_THREAD_ATTACH: // attach to thread break; case DLL_THREAD_DETACH: // detach from thread break; } return TRUE; // succesful } 經過編譯後,我得到了"DllTest.dll"。 接著開啟一個Console application project,編寫下面的程式碼來嘗試使用DLL中 HelloWorld()函式: #include <iostream> #include <windows.h> using namespace std; int main() { HMODULE DllHandle; DllHandle = LoadLibrary("DllTest.dll"); if(DllHandle != NULL) { FARPROC FuncAddr; FuncAddr = GetProcAddress(DllHandle,"HelloWorld"); if(FuncAddr != NULL) { FuncAddr(); } else { cout<<"Function載入失敗:"<<GetLastError()<<endl; } } else { cout<<"DLL載入失敗!"<<endl; } FreeLibrary(DllHandle); system("PAUSE"); return 0; } 編譯完成後將執行檔與DllTest.dll放再同一個目錄下並執行,發現程式可以載入 DllTest.dll,但卻找不到HelloWorld()這個函式,查閱相關文章,發現有可能是 因為C++為了支援函式多載,所以在編譯時對函式名稱動了手腳,但是在製作DLL時 我也使用extern "C"來避免這個狀況了,請問我是不是還遺漏什麼或是哪裡使用錯 誤的方法了呢? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 203.67.181.135 ※ 編輯: icetofux 來自: 203.67.181.135 (07/30 16:54) ※ 編輯: icetofux 來自: 203.67.181.135 (07/30 16:56)

07/30 17:37, , 1F
#define BUILD_DLL 1
07/30 17:37, 1F

07/30 17:38, , 2F
HelloWorld函數要加DLL_EXPORT
07/30 17:38, 2F
※ 編輯: icetofux 來自: 203.67.181.135 (07/30 17:48)

07/30 17:49, , 3F
謝謝你,成功了,我另外把程式碼也修正過了。
07/30 17:49, 3F
文章代碼(AID): #1ASLmUQJ (C_and_CPP)