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

时间:2011-06-08 01:43:14

标签: python callback python-3.x type-conversion ctypes

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

2 个答案:

答案 0 :(得分:2)

这有点像黑客,但它可能适合你。希望其他人能以更干净的方式进入...

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

答案 1 :(得分:0)

我最近一直在查看ctypes代码,以为我可能能够解决这个问题。执行此操作的c代码位于callproc.c(此处为source for 2.7.2)。

来源的相关评论:

  

5 。如果存在“转换器”(转换器是一系列argtypes'   from_param方法),用于每个项目   'callargs'转换器被称为和   结果传递给ConvParam。如果   每个都没有“转换器”   参数直接传递给   ConvParm。

这就是卢克所说的,所以他给的东西可能不是黑客。