2 回答

TA貢獻1848條經驗 獲得超6個贊
LoadLibrary不會做你認為它做的事情。它加載DLL到當前進程的內存,但它并不會神奇地導入它定義的功能!這是不可能的,因為LoadLibrary在運行時調用時,鏈接器會在編譯時解析函數調用(請記住,C ++是一種靜態類型語言)。
您需要一個單獨的WinAPI函數來獲取動態加載函數的地址:GetProcAddress。
例
#include <windows.h>
#include <iostream>
/* Define a function pointer for our imported
* function.
* This reads as "introduce the new type f_funci as the type:
* pointer to a function returning an int and
* taking no arguments.
*
* Make sure to use matching calling convention (__cdecl, __stdcall, ...)
* with the exported function. __stdcall is the convention used by the WinAPI
*/
typedef int (__stdcall *f_funci)();
int main()
{
HINSTANCE hGetProcIDDLL = LoadLibrary("C:\\Documents and Settings\\User\\Desktop\\test.dll");
if (!hGetProcIDDLL) {
std::cout << "could not load the dynamic library" << std::endl;
return EXIT_FAILURE;
}
// resolve function address here
f_funci funci = (f_funci)GetProcAddress(hGetProcIDDLL, "funci");
if (!funci) {
std::cout << "could not locate the function" << std::endl;
return EXIT_FAILURE;
}
std::cout << "funci() returned " << funci() << std::endl;
return EXIT_SUCCESS;
}
此外,您應該正確地從DLL 導出您的函數。這可以這樣做:
int __declspec(dllexport) __stdcall funci() {
// ...
}
正如Lundin指出的那樣,如果您不再需要它,那么將句柄釋放到庫中是一種很好的做法。如果沒有其他進程仍然擁有同一DLL的句柄,這將導致它被卸載。
- 2 回答
- 0 關注
- 737 瀏覽
添加回答
舉報