使用 ctypes windll 卸载 64 位 dll 时出错 [英] error when unload a 64bit dll using ctypes windll

查看:28
本文介绍了使用 ctypes windll 卸载 64 位 dll 时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现这里有几篇关于使用 ctypes 卸载 dll 的帖子,我完全按照所说的方式工作从 ctypes 导入 *

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)

但是,我使用的是 64 位 python 并且我的 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'的长整数(int64),所以这是否意味着windll.kernel32只处理int32句柄?谷歌搜索显示 kernal32 也适用于 64 位窗口.那我该怎么处理呢?

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 intlong(在 Python 3 中重命名为 int)的默认转换是 C longcode>,随后被转换为 C int.即使在 64 位 Windows 上,Microsoft 也使用 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 位 long(即几乎所有其他 64 位操作系统)的平台上,将指针作为 Python 整数传递而不定义函数的 argtypes实际上可能会导致进程出现段错误.对 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆