python-3.x - 使用 ctypes 将带有省略号样式的 varargs 的 c 函数转换为等效的 python

标签 python-3.x ctypes variadic-functions ellipsis

我有一个带有以下签名的 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 允许额外的参数,但您可能必须提示如何正确地编码参数。如果没有特定的 argtypesctypes 将假定 int 参数转换为 c_intc_char_p对于bytesc_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/

相关文章:

c - 枚举类型会进行默认参数提升吗?

python - 使用 ctypes 获取 `time_t` 的类型/大小

c++ - 用 Python+ctypes、segfault 包装 C++ 动态数组

c - 字符是否作为整数传递给被调用的函数?

python - 如何通过 sys.argv 执行函数

python - 在python中调用C程序函数-段错误

c - 用于支持和不支持 VARIADIC 的编译器的 printf 宏

python - 将 str 类型的字典转换为 float Python

Python设置异常

python - AWS/Python Lambda 函数检查是否存在查询字符串