2 回答

TA貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超6個(gè)贊
LoadLibrary不會(huì)做你認(rèn)為它做的事情。它加載DLL到當(dāng)前進(jìn)程的內(nèi)存,但它并不會(huì)神奇地導(dǎo)入它定義的功能!這是不可能的,因?yàn)長oadLibrary在運(yùn)行時(shí)調(diào)用時(shí),鏈接器會(huì)在編譯時(shí)解析函數(shù)調(diào)用(請(qǐng)記住,C ++是一種靜態(tài)類型語言)。
您需要一個(gè)單獨(dú)的WinAPI函數(shù)來獲取動(dòng)態(tài)加載函數(shù)的地址: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;
}
此外,您應(yīng)該正確地從DLL 導(dǎo)出您的函數(shù)。這可以這樣做:
int __declspec(dllexport) __stdcall funci() {
// ...
}
正如Lundin指出的那樣,如果您不再需要它,那么將句柄釋放到庫中是一種很好的做法。如果沒有其他進(jìn)程仍然擁有同一DLL的句柄,這將導(dǎo)致它被卸載。
- 2 回答
- 0 關(guān)注
- 727 瀏覽
添加回答
舉報(bào)