Albert Albert - 11 days ago 8
Python Question

How to access attributes of ctypes Structure as if they were ctypes and not via the given wrapper?

This is inconsistent:

from ctypes import *

class S(Structure):
_fields_ = [("x", POINTER(c_int)), ("y", c_int)]

o = S()
print o.x
print o.y


which returns

<__main__.LP_c_int object at 0x10d3d08c0>
0


So in one case, it returns a
ctypes
type, in the other case, it returns directly the value.

I have some more generic code where I always need to pass a
ctypes
type instance (which is also writeable, i.e. writing to it would mean to modify
o
in the above example). For
o.x
, this is ok. But not for
o.y
.

How can I get the
c_int
instance of
o.y
?

Answer

From the _ctypes source, it seems it doesn't do this clever automatic conversion for simple ctypes instances when they are wrapped.

So one (ugly) solution is this:

from ctypes import *

def WrapClass(c):
    class C(c): pass
    C.__name__ = "wrapped_" + c.__name__
    return C

class S(Structure):
    _fields_ = [("x", POINTER(c_int)), ("y", WrapClass(c_int))]

o = S()
print o.x
print o.y
print o.y.value