Cython compilation error for a free function (Cannot convert Python object argument to type "FooBar *")

I am using Cython (0.15.2) to create an extension for Python (2.6.5). I created a pxd file and a pyx file. Here is the contents of my pyx file:

cimport capifuncs cdef class myArray: cdef capifuncs.myArray *_my_array def __cinit__(self, size): self._my_array = capifuncs.array_new(size) if (self._my_array is NULL): raise MemoryError() def __dealloc__(self): if self._my_array is not NULL: capifuncs.array_free(self._my_array) def __bool__(self): return not capifuncs.IsEmpty(self._my_array) ############################## # Array methods # ############################## cpdef getItem(self, unsigned int pos): if capifuncs.IsEmpty(self._my_array): raise IndexError("Array is empty") #if (): # raise IndexError("Array bounds exceeded") return capifuncs.array_get_item(self._my_array, pos) cpdef setItem(self, unsigned int pos, double val): if capifuncs.IsEmpty(self._my_array): raise IndexError("Array is empty") #if (): # raise IndexError("Array bounds exceeded") capifuncs.array_set_item(self._my_array, pos, val) # Free functions cpdef long someCAPIFuncCall(capifuncs.FooBar *fb, capifuncs.myArray *arr, long start, long stop): return capifuncs.doSomethingInteresting(fb, arr, start, stop) 

If I comment on a free (i.e. non-member) function definition statement, the code compiles correctly and an extension is created. However, if I uncomment it and try to compile the file, I get the following error message:

cafuncs.pyx: 64: 23: Unable to convert Python object argument to type 'FooBar *'

What is the reason for this and how to fix it?

+6
source share
1 answer

A function defined as cpdef can be called from both Python and C.

If the arguments are declared as C data types, Cython will try to automatically convert the objects passed to the function when called from Python. But such conversions are possible only for numeric and string types - all other types lead to a compile-time error.

Did you want to raise this function in Python? If not, define it using cdef .

Otherwise, you will need to create wrappers for the types of C that you want to pass to and from Python. See Cython Tutorials for some examples of how to do this.

+4
source

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


All Articles