Suppose I have the following simple example of C++ inheritance in file.h
:
class Base {};
class Derived : public Base {};
Then, the following code compiles; that is, I can assign std::shared_ptr<Derived>
to std::shared_ptr<Base>
:
Derived* foo = new Derived();
std::shared_ptr<Derived> shared_foo = std::make_shared<Derived>(*foo);
std::shared_ptr<Base> bar = shared_foo;
Let's also say I've added the types to a decl.pxd
:
cdef extern from "file.h":
cdef cppclass Base:
pass
cdef cppclass Derived(Base):
pass
Then, what I'm trying to do is mimic the above C++ assignment in Cython in a file.pyx
:
cimport decl
from libcpp.memory cimport make_shared, shared_ptr
def do_stuff():
cdef decl.Derived* foo = new decl.Derived()
cdef shared_ptr[decl.Derived] shared_foo = make_shared[decl.Derived](foo)
cdef shared_ptr[decl.Base] bar = shared_foo
Unlike the C++ case, this now fails with the following error (using Cython 3.0a6):
cdef shared_ptr[decl.Base] bar = shared_foo
^
---------------------------------------------------------------
Cannot assign type 'shared_ptr[Derived]' to 'shared_ptr[Base]'
Should I expect this behavior? Is there any way to mimic what the C++ examples does with Cython?
Edit: Cf. the comments to the accepted answer below, the relevant functionality has been added to Cython and is available as of version 3.0a7.