I\'m trying to use Python\'s C-Types to call GetModuleHandleA on the kernel32 library. I\'d like to get a handle to the library so I can use it to call GetProcAddress for L
The handle is stored in kernel32._handle
. Calling GetModuleHandle
should return the same value, but make sure you set restype
and argtypes
for type safety [*]:
import ctypes
from ctypes import wintypes
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
kernel32.GetModuleHandleW.restype = wintypes.HMODULE
kernel32.GetModuleHandleW.argtypes = [wintypes.LPCWSTR]
hMod = kernel32.GetModuleHandleW('kernel32.dll')
Notice the 'W' suffix instead of 'A'. Python 3 uses Unicode strings, for which ctypes creates a c_wchar_p
(LPCWSTR
). There's no reason to call the [A]NSI version since it's just a wrapper around the [W]ide string version. But if you must, then you need to use bytes:
kernel32.GetModuleHandleA.restype = wintypes.HMODULE
kernel32.GetModuleHandleA.argtypes = [wintypes.LPCSTR]
hMod = kernel32.GetModuleHandleA(b'kernel32.dll')
[*] I recommend using kernel32 = WinDLL('kernel32', use_last_error=True)
instead of windll.kernel32
. This avoids conflicts with other modules that use windll
. It also enables protection for the thread's LastErrorValue
. In this case, use ctypes.get_last_error()
and ctypes.set_last_error(err)
instead of directly calling WinAPI GetLastError
and SetLastError
.