How can I convert a Python object argument in a Cython method defined using def
to a C++ type? I am attempting to provide a Cython wrapper class for a C++ library, as described in the Using C++ in Cython section of the Cython documentation.
Here is an example that demonstrates my issue.
File foo.h
:
namespace ns {
class Foo:
public:
Foo();
dosomething(std::shared_ptr<Bar>);
}
File bar.h
:
namespace ns {
class Bar:
public:
Bar();
}
File foo.pyx
:
from libcpp.memory cimport shared_ptr
cdef extern from 'bar.h' namespace 'ns':
cdef cppclass Bar:
Bar() except +
cdef extern from 'foo.h' namespace 'ns':
cdef cppclass Foo:
Foo() except +
void dosomething(shared_ptr[Bar])
cdef class PyBar:
cdef Bar* thisptr
def __cinit__(self):
self.thisptr = new Bar()
def __dealloc__(self):
del self.thisptr
cdef class PyFoo:
cdef Foo* thisptr
def __cinit__(self):
self.thisptr = new Foo()
def __dealloc__(self):
del self.thisptr
def dosomething(self, bar):
self.thisptr.dosomething(bar)
File setup.py
:
from setuptools import Extension
from setuptools import setup
from Cython.Build import cythonize
extensions = [
Extension(
'foo',
sources=[
'foo.pyx',
'foo.cpp',
'bar.cpp',
],
language='c++',
include_dirs=['.'],
extra_compile_args=['-std=c++11'],
),
]
setup(
ext_modules=cythonize(extensions),
)
The error that occurs when I try to compile this:
$ python setup.py build_ext
Compiling foo.pyx because it changed.
[1/1] Cythonizing foo.pyx
Error compiling Cython file:
------------------------------------------------------------
...
def __dealloc__(self):
del self.thisptr
def dosomething(self, bar):
self.thisptr.dosomething(bar)
^
------------------------------------------------------------
foo.pyx:38:33: Cannot convert Python object to 'shared_ptr[Bar]'