繁体   English   中英

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

[英]Prevent automatic type conversion in ctypes callback functions

当使用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))))

产生( python3 cfunctype_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)

这有点小技巧,但它可能对你有用。 希望其他人会以更清洁的方式加入..

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))))

..和 output 是:

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

我最近一直在看 ctypes 代码,以为我可以弄清楚这一点。 执行此操作的 c 代码位于 callproc.c (这是2.7.2 的源代码)。

消息来源的相关评论:

5 . 如果存在“converters”(converters 是 argtypes 的 from_param 方法的序列),则为“callargs”中的每个项目调用转换器并将结果传递给 ConvParam。 如果“转换器”不存在,则每个参数都直接传递给 ConvParm。

这几乎就是卢克所说的,所以他给出的可能不是黑客。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM