FreeLibrary
takes a handle, defined as a C void *
pointer. Refer to Windows Data Types. Set this in the function pointer's argtypes
:
import ctypes
from ctypes import wintypes
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
kernel32.FreeLibrary.argtypes = [wintypes.HMODULE]
The default conversion of a Python int
or long
(renamed int
in Python 3) is to a C long
, which is subsequently cast to a C int
. Microsoft uses a 32-bit long
even on 64-bit Windows, which is why the conversion raises OverflowError
.
On platforms that have a 64-bit long
(i.e. pretty much every other 64-bit OS), passing a pointer as a Python integer without defining the function's argtypes
may actually segfault the process. The initial conversion to long
works fine because it's the same size as a pointer. However, subsequently casting to a 32-bit C int
may silently truncate the value.