使用ctypes windll卸载64位dll时出错 [英] error when unload a 64bit dll using ctypes windll
问题描述
我发现这里有几篇关于使用ctypes卸载dll的文章,我完全按照据说的方式从ctypes import工作
*
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)
但是我在python 64位,并且我的dll也针对x64进行了编译,我从上面的最后一行得到了一个错误:
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
,我检查了句柄是'8791681138688'的long int(int64),那么这是否意味着windll.kernel32仅处理int32句柄? Google搜索显示kernal32也适用于64位Windows。那么我应该如何处理呢?
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
需要一个句柄,已定义作为C void *
指针。请参考 Windows数据类型。在函数指针的 argtypes
中进行设置:
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]
Python int
或 long
(在Python 3中重命名为 int
)为C long
,随后将其转换为C int
。 Microsoft即使在64位Windows上也使用32位 long
,这就是为什么转换会引发 OverflowError
的原因。
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
.
在具有64位长
(即几乎所有其他64位OS)的平台上,一个没有定义函数的 argtypes
的Python整数指针实际上可能会隔离进程。初始转换为 long
的效果很好,因为它的大小与指针相同。但是,随后强制转换为32位C int
可能会无声地截断该值。
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.
这篇关于使用ctypes windll卸载64位dll时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!