Prevent automatic type conversion in ctypes callback functions

When porting Python functions with type CFUNCTYPE I found that types without pointers are automatically converted as if their <attribute href = "http://docs.python.org/py3k/library/ctypes.html#ctypes._SimpleCData was called. value "rel =" nofollow "> value .

How can I suppress this automatic conversion?

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

What produces ( python3 cfunctype_type_conversion.py ):

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

I would like to:

 {'the_int': c_int(1), 'the_int_p': <__main__.LP_c_int object at 0x2671830>} c_int(3) 
+6
source share
2 answers

This is a little hack, but it might work for you. Hope someone else includes a cleaner way.

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

.. and conclusion:

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

I watched ctypes code recently, thought I could figure it out. The c code that does this is in callproc.c (here is the source for 2.7.2 ).

Relevant comment from source:

5. If "converters" are present (converters are a sequence of arguments) from_param), the callargs converter is called for each element in and the result is passed to ConvParam. If there are no "converters", each argument is passed directly to ConvParm.

This is pretty much what Luke said, so he probably gave it no hack.

0
source

Source: https://habr.com/ru/post/890008/


All Articles