如何解决可以在 Python ctypes 中需要 Windows 句柄的地方传递整数
我有以下代码:
GetForegroundWindow = windll.user32.GetForegroundWindow
GetWindowTextLength = windll.user32.GetWindowTextLengthW
GetWindowText = windll.user32.GetWindowTextW
hwnd = GetForegroundWindow() # Get handle to foreground window. Here hwnd is a Python int.
length = GetWindowTextLength(hwnd) # Get length of the window text in title bar. Here hwnd is expected to be a Windows Handle.
buff = create_unicode_buffer(length + 1) # Create buffer to store the window title buff
GetWindowText(hwnd,buff,length + 1) # Get window title and store in buff
print(buff.value) # print the value of buff
在第 4 行,检索到一个句柄,在 ctypes 中假定它是一个 Python int。在下一行,它被传递到需要 Windows 句柄的地方。 Python 是否会自动将其转换为正确的类型?我们不需要显式转换吗?
解决方法
不,不要假设。在每个函数上设置 .argtypes
和 .restype
以告知 ctypes
参数类型和返回类型是什么。例如,在 64 位 Python 上,句柄是 64 位,假定的 c_int
返回值会将其截断为 32 位。
例如,使用提供的一些预定义 Windows 类型扩展您的代码:
from ctypes import wintypes as w
...
GetForegroundWindow.argtypes = ()
GetForegroundWindow.restype = w.HWND
现在无论操作系统如何,都将返回正确的值。对使用的其他函数重复此操作,将对参数进行类型检查并检查参数数量和返回值是否正确。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。