Ctypes: Mapping A Returned Pointer To A Structure
Solution 1:
I already created a small example of my own. After taking a closer look at the Python code, I could figure out the function header (and I also added some dummy body).
The problem is simple, the function returns a CONNECTOR
pointer, in order to access its members, you need to "dereference" it first, otherwise you'll get the AttributeError
. Here's your code (a little bit modified):
testlib = ctypes.cdll.LoadLibrary("_example.so")
testfunc = testlib.square_array
testfunc.argtype = ctypes.POINTER(CONNECTOR)
testfunc.restype = ctypes.POINTER(CONNECTOR)
pconnector0 = testfunc(ctypes.byref(con[0]))
connector0 = pconnector0.contents
print(connector0.NumberOfRows)
print(connector0.Rows[0].Address)
The "secret" lies in pconnector0.contents
which performs the "dereferencing".
As a side note the line of code y.Rows[0].Address[0]
will trigger an TypeError
because of the [0]
at the end: Address
is an int
and can't be indexed (doesn't define __getitem__
).
Regarding the second approach (calling the function directly), it's the same problem. Here's some working code:
pconnector1 = testlib.square_array(ctypes.byref(con[0]))
connector1 = pconnector1.contents
print(type(connector1))
Note: I used Python 2.7.10 on Win10 x64, but nothing here should be Python version or platform specific.
Post a Comment for "Ctypes: Mapping A Returned Pointer To A Structure"