i found there are several posts here about unloading a dll using ctypes, and i followed exactly the way said to be working from ctypes import *
file = CDLL('file.dll')
# do some stuff here
handle = file._handle # obtain the DLL handle
windll.kernel32.FreeLibrary(handle)
however, i am on python 64 bit and my dll is also compiled for x64, and i got an error from the last line above saying:
argument 1: <class 'OverflowError'>: int too long to convert
and i checked the handle to be a long int (int64) of '8791681138688', so does that mean windll.kernel32 only deals with int32 handle? Google search shows kernal32 is also for 64bit windows. how should i deal with this then?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With