Wrapping c++ shared pointers

931 views
Skip to first unread message

Mario Pezzoni

unread,
Dec 23, 2015, 9:26:33 AM12/23/15
to cython-users
Hi,

I am wrapping a c++ library that returns large objects using std::shared_ptr. I want my python API to return python objects that wrap these shared_ptr.

#
# Python class wrap.
#
cdef class PyObj:
    cdef shared_ptr[CppObj] _ptr

    @staticmethod
    cdef create(shared_ptr[CppObj] ptr):
        cdef PyObj py_obj = PyObj()
        py_obj._ptr = ptr

        return py_obj

#
# Cpp function wrapper, the input variable is a numpy array.
#
cdef test_wrap(mat):
  
    cdef Py_buffer buf
    PyObject_GetBuffer(mat, &buf, PyBUF_FULL)

    cdef shared_ptr[CppObj] obj_ptr = cpp_function(&buf)

    return PyObj.create(obj_ptr)

The compiler always fails with: "Cannot convert 'shared_ptr[CppObj]' to Python object".

How can I wrap c++ shared pointers?

Omer Katz

unread,
Jan 2, 2016, 10:50:42 AM1/2/16
to cython-users
Maybe you need to specify that this is a c++ class like this:
cdef cppclass shared_pointer

Robert Bradshaw

unread,
Jan 2, 2016, 8:28:33 PM1/2/16
to cython...@googlegroups.com
This seems to work for me:

#distutils: language=c++

from libcpp.memory cimport shared_ptr
from cpython.buffer cimport PyObject_GetBuffer, PyBUF_FULL

cdef extern from *:
cdef cppclass CppObj:
pass
cdef shared_ptr[CppObj] cpp_function(Py_buffer *buf)


cdef class PyObj:
cdef shared_ptr[CppObj] _ptr

@staticmethod
cdef create(shared_ptr[CppObj] ptr):
cdef PyObj py_obj = PyObj()
py_obj._ptr = ptr

return py_obj

cdef test_wrap(mat):

cdef Py_buffer buf
PyObject_GetBuffer(mat, &buf, PyBUF_FULL)

cdef shared_ptr[CppObj] obj_ptr = cpp_function(&buf)

return PyObj.create(obj_ptr)

https://gist.github.com/robertwb/1385afaea4df10eb224a
Reply all
Reply to author
Forward
0 new messages