I wanted to got a set of API Native'm using GetProcAddressto. in the method that i use first by GetModuleHandle got the considering DLLHandle then the API address that is my desire,is taken by GetProcAddress. it works for functions in ntdll but for user32 and advapi32 GetModuleHandle function returns null value. for solving this problem, what's your suggestion?

enter code here

HANDLE Proc = GetCurrentProcess();
HMODULE hNtdll = GetModuleHandle(TEXT("ntdll.dll"));
FARPROC function_address = GetProcAddress(hNtdll, function_name);
有帮助吗?

解决方案

GetModuleHandle() requires the DLL to already be loaded:

Retrieves a module handle for the specified module. The module must have been loaded by the calling process.

ntdll.dll will always be loaded but user32.dll and advapi32.dll are not necessarily loaded by default. Based on your description it sounds as though the code calls GetModuleHandle() first, which will fail if the DLL is not already loaded (check the value of GetLastError() in the event of failure).

Use LoadLibrary() for DLLs that are not loaded by default. However, using LoadLibrary() in the event that GetModuleHandle() fails is a dangerous strategy as some other thread in the process could FreeLibrary() the DLL that you have acquired a handle to via GetModuleHandle() (meaning any function addresses that you have acquired via that handle are invalid as the DLL is no longer in memory). Using LoadLibrary(), with the subsequent FreeLibrary(), is a safer approach as it ensures the DLL won't be unloaded until you FreeLibrary() it.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top