Python ctypes 定义函数的类型错误

Python ctypes TypeError for defined function

我有一个已知函数类型定义 wintypes.HANDLE, wintypes.LPVOID,return 值为 wintypes.DWORD

使用 ctypes 我定义了类型和函数并尝试使用 handlelpvoid 参考进行调用:

ftype = CFUNCTYPE(wintypes.HANDLE, wintypes.LPVOID, wintypes.DWORD)
function = ftype(address)

base = wintypes.LPVOID(0x0)
ptr = function(GetCurrentProcess(), byref(base))

但是,执行时出现错误: ctypes.ArgumentError: argument 2: <class 'TypeError'>: wrong type

谁能帮我找出问题所在?

如果不是定义的lpvoid,我应该传递什么type

这是一个最小的例子。我用描述的函数签名创建了一个 DLL,并提取了地址来演示 Python 代码。

#include <windows.h>
#include <stdio.h>

#ifdef _WIN32
#   define API __declspec(dllexport)
#else
#   define API
#endif

API DWORD function(HANDLE h, LPVOID pv) {
    printf("h=%p pv=%p\n", h, pv);
    return 1;
}
from ctypes import *
from ctypes import wintypes

dll = CDLL('./test')
address = addressof(dll.function)

# return value is the FIRST parameter to CFUNCTYPE
ftype = CFUNCTYPE(wintypes.DWORD, wintypes.HANDLE, wintypes.LPVOID)

# ftype(address) doesn't expect an unwrapped C address, but a Python function,
# so I used from_address() instead.
function = ftype.from_address(address)

ret = function(0x123,None) # None can be used for a null pointer
print(ret)

输出:

h=0000000000000123 pv=0000000000000000
1