防止ctypes回调函数中的自动类型转换

6 投票
2 回答
767 浏览
提问于 2025-04-16 19:08

在用 CFUNCTYPE 类型来包装 Python 函数时,我发现一些不是指针的类型会自动转换,就好像它们的 value 属性被调用了一样。

我该怎么才能停止这种自动转换呢?

from ctypes import *

funcspec = CFUNCTYPE(c_int, c_int, POINTER(c_int))

@funcspec
def callback(the_int, the_int_p):
    print(vars())
    return 3

print(callback(c_int(1), byref(c_int(2))))

这段代码会产生 (python3cfunctype_type_conversion.py):

{'the_int': 1, 'the_int_p': <__main__.LP_c_int object at 0x2671830>}
3

我想要的是:

{'the_int': c_int(1), 'the_int_p': <__main__.LP_c_int object at 0x2671830>}
c_int(3)

2 个回答

1

我最近在研究ctypes的代码,想着也许能搞明白这个问题。处理这个的C语言代码在callproc.c文件里(这是2.7.2版本的源代码)。

源代码中的一个相关评论:

5。如果存在'converters'(converters是一系列argtypes的from_param方法),那么对于'callargs'中的每个项目,都会调用转换器,然后将结果传递给ConvParam。如果没有'converters',那么每个参数就会直接传递给ConvParam。

这基本上就是Luke所说的,所以他给出的内容可能并不是个黑科技。

3

这有点像是个小窍门,但可能对你有用。希望其他人能提供更简单的方法。

from ctypes import *

class c_int_hack(c_int):
    def from_param(self, *args):
        return self

funcspec = CFUNCTYPE(c_int, c_int_hack, POINTER(c_int))

@funcspec
def callback(the_int, the_int_p):
    print(vars())
    print(the_int.value)
    return 3

print(callback(c_int(1), byref(c_int(2))))

..输出结果是:

{'the_int': <c_int_hack object at 0xb7478b6c>, 'the_int_p': <__main__.LP_c_long object at 0xb747892c>}
1
3

撰写回答