Ctypes: how to disable simple types autoconversion

When a value of simple type is returned from a ctypes function call, it gets converted to a plain python type. For example,

>>> from ctypes import *
>>> c = cdll.LoadLibrary(None)
>>> c.abs(-1)
1
>>> c.llabs(-1)
1

This is often inconvenient because the exact type information is lost and results cannot be passed to functions that don’t have argtypes set.

I tried to override the __ctypes_from_outparam__ method, but it did not help

>>> c_longlong.__ctypes_from_outparam__ = lambda x: x
>>> f = c.llabs
>>> f.restype = c_longlong
>>> f(-1)
1

Is there a way to make c.llabs return c_longlong?

It looks like I’ve found a solution. I need to subclass the data type:

>>> from ctypes import *
>>> c = cdll.LoadLibrary(None)
>>> f = c.llabs
>>> class LL(c_longlong):
...   pass
...
>>> f.restype = LL
>>> f(-1)
<LL object at 0x10970a3b0>
>>> f(-1).value
1
1 Like