我有一个带有以下签名的 c 函数
func(enum_type level, const char* 函数, const int line, const char* file, const char* msg, ...)
需要在 ctypes 装饰器调用中传递的等效参数类型是什么?
我尝试过这样的事情
@CFUNCTYPE(无,级别,POINTER(c_char),c_int,POINTER(c_char),POINTER(c_char),“...”)
因为“...”不是 ctypes 类型,不知道如何处理这个问题
最佳答案
不要为 ...
指定任何内容。 ctypes
允许额外的参数,但您可能必须提示如何正确地编码参数。如果没有特定的 argtypes
,ctypes
将假定 int
参数转换为 c_int
,c_char_p
对于bytes
,c_wchar_p
对于str
,对于其他参数要么失败,要么做错误的事情。如果需要,请手动进行转换。示例:
import ctypes as ct
dll = ct.CDLL('msvcrt') # For printf/wprintf on Windows
dll.wprintf.argtypes = ct.c_wchar_p, # int wprintf(const wchar_t*, ...)
dll.wprintf.restype = ct.c_int
dll.printf.argtypes = ct.c_char_p, # int printf(const char*, ...)
dll.printf.restype = ct.c_int
dll.wprintf("%s, %d, %lf\n", "hello", 123, ct.c_double(3.14))
handle = 0x123456789 # >32-bit. Pointers are 64-bit on my system.
dll.wprintf("%p\n", ct.c_void_p(handle))
dll.printf(b"%s, %s!\n", b'Hello', b'world')
输出:
hello, 123, 3.140000
0000000123456789
Hello, world!
如果删除 ct.c_double()
或 ct.c_void_p
转换,ctypes
会提示它不知道如何编码(marshal)float
,并提示 int
太大,因为它大于 c_int
可以容纳的大小。
关于python-3.x - 使用 ctypes 将带有省略号样式的 varargs 的 c 函数转换为等效的 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69884045/