在Python ctypes中需要Windows句柄的位置可以传递int吗

在Python ctypes中需要Windows句柄的位置可以传递int吗,python,ctypes,Python,Ctypes,我有以下代码: GetForegroundWindow = windll.user32.GetForegroundWindow GetWindowTextLength = windll.user32.GetWindowTextLengthW GetWindowText = windll.user32.GetWindowTextW hwnd = GetForegroundWindow() # Get handle to foreground window. Here hwnd is a Pyth

我有以下代码:

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位

例如,使用提供的一些预定义窗口类型扩展代码:

from ctypes import wintypes as w
...
GetForegroundWindow.argtypes = ()
GetForegroundWindow.restype = w.HWND
现在,无论操作系统如何,都将返回正确的值。对使用的其他函数重复此操作,将对参数进行类型检查,并检查参数数量和返回值是否正确