Home >Backend Development >C++ >How to Access DLL Functions Using LoadLibrary and GetProcAddress?
Dynamically Loading Functions from DLLs
Question:
How can the LoadLibrary handle be used to access functions defined in a DLL?
LoadLibrary loads a DLL into memory but does not automatically import its functions. This requires a second WinAPI function: GetProcAddress.
Example:
#include <windows.h> #include <iostream> 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 using GetProcAddress 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; // Free the library handle when no longer needed FreeLibrary(hGetProcIDDLL); return EXIT_SUCCESS; }
Dll Export:
Ensure the function is correctly exported from the DLL using the __declspec(dllexport) and __stdcall attributes:
int __declspec(dllexport) __stdcall funci() { // ... }
The above is the detailed content of How to Access DLL Functions Using LoadLibrary and GetProcAddress?. For more information, please follow other related articles on the PHP Chinese website!