【发布时间】:2021-08-10 01:19:45
【问题描述】:
假设我在file.h 中有以下简单的 C++ 继承示例:
class Base {};
class Derived : public Base {};
然后,以下代码编译;也就是说,我可以将std::shared_ptr<Derived>分配给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;
假设我已将类型添加到 decl.pxd:
cdef extern from "file.h":
cdef cppclass Base:
pass
cdef cppclass Derived(Base):
pass
然后,我要做的是在 file.pyx 中模仿 Cython 中的上述 C++ 赋值:
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
与 C++ 案例不同,现在失败并出现以下错误(使用 Cython 3.0a6):
cdef shared_ptr[decl.Base] bar = shared_foo
^
---------------------------------------------------------------
Cannot assign type 'shared_ptr[Derived]' to 'shared_ptr[Base]'
我应该期待这种行为吗?有什么方法可以模仿 C++ 示例对 Cython 的作用?
编辑:参见。对于下面接受的答案的 cmets,相关功能已添加到 Cython,并且从 3.0a7 版本开始可用。
【问题讨论】:
标签: python c++ inheritance cython shared-ptr