I am trying to write a wrapper to a native library in Linux. Problem is this:
definition in c:
int mymethod(mystruct* ptr)
in python:
_lib.mymethod.argtypes = (ctypes.POINTER(mystruct),)
_lib.mymethod.restype = ctypes.c_int
s = mystruct()
_lib.mymethod(ctypes.byref(s))
# raises: expected LP_mystruct instance instead of pointer to mystruct
_lib.mymethod(ctypes.pointer(s))
# raises expected LP_mystruct instance instead of LP_mystruct
errors. How to pass a structure as a pointer to a native method ?
Thanks.
Mete
The problem is that the higher level “POINTER” from ctypes is, in Python, a different object than “a generic pointer” (
ctypes.CArgObjectbyctypes.byref)which is returned or a single number representing a memory address (which is what is returned by ctype’sadrresof) – you can either annotate your function to receive a`ctypes.c_voidpand call it with_lib.mymethod(ctypes.addressof(a))instead –Or if you want to work on the stronged-typed side to avoid errors that would crash Python (a type error raises a Python exception instead – a wrong parameter passed to a C unction would cause a segmentation fault on the Python interpreter itself), you have to create a variable to hold the new “type” which is a POINTER to your structure – and then create an instance of this type with the address of your structure: