我正在尝试通过试验某些 Windows API 来尝试使用 Python 和 ctypes。我有一段失败的代码,我不知道为什么。我已经按照 MSDN 文档设置了所有 argtypes 和返回类型。我得到的错误是:TypeError: an integer is required (got type LP_c_long)
。您可以在输出部分看到所有错误。据我所知,argtypes 和返回类型是正确的,我不确定需要修复什么。
from ctypes import *
from ctypes import wintypes as w
user32 = windll.user32
kernel32 = windll.kernel32
HOOKPROC = WINFUNCTYPE(HRESULT, c_int, w.WPARAM, w.LPARAM) # Callback function prototype
user32.SetWindowsHookExW.argtypes = [c_int, HOOKPROC, w.HINSTANCE, w.DWORD]
user32.SetWindowsHookExW.restype = w.HHOOK
kernel32.GetModuleHandleW.argtypes = [w.LPCWSTR]
kernel32.GetModuleHandleW.restype = w.HANDLE
user32.GetMessageW.argtypes = [w.LPMSG, w.HWND, w.UINT, w.UINT]
user32.GetMessageW.restype = w.BOOL
user32.CallNextHookEx.argtypes = [w.HHOOK, c_int, w.WPARAM, w.LPARAM]
user32.CallNextHookEx.restype = w.LPLONG
def hook_procedure(nCode, wParam, lParam):
print("Hello...")
#return user32.CallNextHookEx(hook, nCode, wParam, lParam)
return user32.CallNextHookEx(hook, nCode, wParam, c_lParam)
ptr = HOOKPROC(hook_procedure)
hook = user32.SetWindowsHookExW(
13,
ptr,
kernel32.GetModuleHandleW(None),
0
)
msg = w.MSG() # MSG data structure
user32.GetMessageW(byref(msg), 0, 0, 0) # Wait for messages to be posted
输出:
Hello...
Traceback (most recent call last):
File "_ctypes/callbacks.c", line 262, in 'converting callback result'
TypeError: an integer is required (got type LP_c_long)
Exception ignored in: <function hook_procedure at 0x0000025C469551F0>
答案 0 :(得分:1)
问题出在这里:
const _counterReducer = createReducer(
// initialize it
initialState = {count: number} ,
// your accessor need to access the values inside the state
on(increment, (state) => parseInt(state.count)++),
on(decrement, (state) => parseInt(state.count)--),
on(reset, (parseInt(state.count)) => 0)
);
user32.CallNextHookEx.restype = w.LPLONG
返回一个 CallnextHookEx
,它在 C 中被定义为一个 LRESULT
。那不是指针,而是指针大小的整数(32 位系统上为 4 个字节,64 位系统上为 8 个字节)。 LONG_PTR
没有该类型,但 wintypes
具有相同的定义 (LONG_PTR),因此您可以使用以下定义作为适用于 32 位和 64 位 Python 的定义:
LPARAM