Error unloading 64 bit dll using ctypes windll

I found that here are a few dll unloading messages using ctypes, and I have precisely followed how this works from the 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 64-bit python, 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 descriptor as long int (int64) '8791681138688', does this mean that windll.kernel32 only works with the int32 descriptor? A Google search shows that kernal32 is also designed for 64-bit windows. how should i deal with this then?

+3
source share
1 answer

FreeLibrary takes a handle defined as a pointer to C void * . See Windows Data Types . Set this in the argtypes function argtypes :

 import ctypes from ctypes import wintypes kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) kernel32.FreeLibrary.argtypes = [wintypes.HMODULE] 

The default conversion of Python int or long (renamed int in Python 3) refers to C long , which is then passed to C int . Microsoft uses a 32-bit long even on 64-bit Windows, so the conversion raises an OverflowError .

On platforms with a 64-bit long (i.e. almost any other 64-bit OS), passing the pointer as a Python integer without defining the argtypes function can actually secure the process. The initial conversion to long works fine because it is the same size as the pointer. However, subsequent casting to a 32-bit C int may silently truncate the value.

+3
source

Source: https://habr.com/ru/post/1433877/


All Articles