Cython: Passing pointer created by Python wrapper class to C function

Question:

I am following the Cython Documentation to define a class that is created from an existing C pointer:

# Example C struct
ctypedef struct my_c_struct:
    int a
    int b


cdef class WrapperClass:
    """A wrapper class for a C/C++ data structure"""
    cdef my_c_struct *_ptr
    cdef bint ptr_owner

    def __cinit__(self):
        self.ptr_owner = False

    def __dealloc__(self):
        # De-allocate if not null and flag is set
        if self._ptr is not NULL and self.ptr_owner is True:
            free(self._ptr)
            self._ptr = NULL

    # Extension class properties
    @property
    def a(self):
        return self._ptr.a if self._ptr is not NULL else None

    @property
    def b(self):
        return self._ptr.b if self._ptr is not NULL else None

    @staticmethod
    cdef WrapperClass from_ptr(my_c_struct *_ptr, bint owner=False):
        """Factory function to create WrapperClass objects from
        given my_c_struct pointer.

        Setting ``owner`` flag to ``True`` causes
        the extension type to ``free`` the structure pointed to by ``_ptr``
        when the wrapper object is deallocated."""
        # Call to __new__ bypasses __init__ constructor
        cdef WrapperClass wrapper = WrapperClass.__new__(WrapperClass)
        wrapper._ptr = _ptr
        wrapper.ptr_owner = owner
        return wrapper

    @staticmethod
    cdef WrapperClass new_struct():
        """Factory function to create WrapperClass objects with
        newly allocated my_c_struct"""
        cdef my_c_struct *_ptr = <my_c_struct *>malloc(sizeof(my_c_struct))
        if _ptr is NULL:
            raise MemoryError
        _ptr.a = 0
        _ptr.b = 0
        return WrapperClass.from_ptr(_ptr, owner=True)

This works great for creating objects from an existing pointer, but I’m having trouble using the new_struct method of this class to create new pointers that can be passed to C functions:

cdef inner_function(my_c_struct *pointer):
    return pointer.a + pointer.b

def outer_function():
    wrapper_class = WrapperClass.new_strct()
    result = inner_function(wrapper_class._ptr)
    return result

The code above results in the compile error: Cannot convert Python object to 'my_c_struct *'. Does anyone know how to modify the code in the second block so that I can compile and run outer_function? I see the note in this section of the Cython documentation:

Attempts to use pointers in a Python signature will result in errors like: Cannot convert 'my_c_struct *' to Python object

but am unsure how to fix the issue in this case.

Asked By: Forrest Williams

||

Answers:

As stated by @ead in the comment above:

It probably should be cdef WrapperClass wrapper_class = WrapperClass.new_strct() for Cython to understand that wrapper_class.ptr is not a python object

Answered By: Forrest Williams
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.