gpt4 book ai didi

python - 如何在 Python 中处理 PyCapsule 类型

转载 作者:行者123 更新时间:2023-12-04 02:07:58 42 4
gpt4 key购买 nike

我正在尝试传递对象

QtGui.QWidget.effectiveWinId() 


win32gui.SetWindowLong()

EffectiveWinId() 正在返回:
<capsule object NULL at 0x027C9BF0>
<class 'PyCapsule'>

并且 SetWindowLong() 需要一个 PyHANDLE(文档说它“应该”也接受一个整数)
TypeError: The object is not a PyHANDLE object

所以我的问题是如何从 PyCapsule 对象中获取值并检查其是否为 NULL?似乎 PyCapsule 都是 C 代码的内部 API。

我还发现这个错误与我想要的 Python 2.X PyCObject 类似,它在 Python 3.x 中不存在: http://srinikom.github.io/pyside-bz-archive/show_bug.cgi?id=523#c18

最佳答案

好吧,我设法弄清楚了:

# ...
capsule = self.effectiveWinId()
ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.c_void_p
ctypes.pythonapi.PyCapsule_GetPointer.argtypes = [ctypes.py_object, ctypes.c_char_p]
handle = ctypes.pythonapi.PyCapsule_GetPointer(capsule, None)
win32gui.SetWindowLong(handle, win32con.GWL_WNDPROC, self.new_window_procedure)
# ...

这是一个处理覆盖 win32 窗口过程的 python 类:
import win32con
import win32gui
import win32api
import ctypes
import pywintypes

def convert_capsule_to_int(capsule):
ctypes.pythonapi.PyCapsule_GetPointer.restype = ctypes.c_void_p
ctypes.pythonapi.PyCapsule_GetPointer.argtypes = [ctypes.py_object, ctypes.c_char_p]
return ctypes.pythonapi.PyCapsule_GetPointer(capsule, None)

class WindowProcedure(object):
self.handle_WM_DESTROY = False
def __init__(self, handle):
if isinstance(handle, int) or isinstance(handle, type(pywintypes.HANDLE())):
self.handle = handle
else:
self.handle = convert_capsule_to_int(handle)
self.old_proc = win32gui.GetWindowLong(self.handle, win32con.GWL_WNDPROC)
if not self.old_proc:
raise RuntimeError("Failed to set/get window procedure!")
if not win32gui.SetWindowLong(self.handle, win32con.GWL_WNDPROC, self.new_window_procedure):
raise RuntimeError("Failed to set/get window procedure!")

def handle_old_procedure(self, hwnd, msg, wparam, lparam):
# For some reason the executable would hang after a QtGui.QWidget exit
# so I'm forcing it here if self.handle_WM_DESTROY is true
if msg == win32con.WM_DESTROY and self.handle_WM_DESTROY:
win32gui.DestroyWindow(hwnd)
return 0
return win32gui.CallWindowProc(self.old_proc, hwnd, msg, wparam, lparam)

关于python - 如何在 Python 中处理 PyCapsule 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22497295/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com