Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
917 views
in Technique[技术] by (71.8m points)

python - error when unload a 64bit dll using ctypes windll

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...