You need to enable JavaScript to run this app. C++继承场景下Cython中std::shared_ptr类型赋值问题咨询
优惠活动
大模型
产品
解决方案
定价
更多

C++继承场景下Cython中std::shared_ptr类型赋值问题咨询

Cython中shared_ptr<Derived>无法赋值给shared_ptr<Base>问题说明

问题复现

假设我有如下定义在file.h中的C++继承简单示例:

class Base {};
class Derived : public Base {};

如下C++代码可以正常编译,即我可以将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]'

问题解答

是否为预期行为

该报错在Cython 3.0a6及更早版本中属于预期表现。旧版本Cython的shared_ptr绑定未实现C++标准中智能指针的协变转换逻辑,无法自动识别派生类到基类的shared_ptr类型转换。

解决方案

  • 若使用Cython 3.0a7及更高版本:无需修改代码,原写法可直接正常编译运行,和原生C++行为完全一致。
  • 若必须使用3.0a6及更早版本,可通过手动类型转换实现相同效果,推荐两种安全写法:
    1. 显式调用static_pointer_cast转换(优先推荐,可保留智能指针的引用计数管理逻辑)
    # 开头补充导入
    from libcpp.memory cimport static_pointer_cast
    
    # 赋值处修改为
    cdef shared_ptr[decl.Base] bar = static_pointer_cast[decl.Base](shared_foo)
    
    1. 通过原始指针中转
    cdef shared_ptr[decl.Base] bar = shared_ptr[decl.Base](shared_foo.get())
    

编辑说明:相关智能指针协变转换功能已正式加入Cython,自3.0a7版本开始默认支持。

内容的提问来源于stack exchange,提问作者fuglede

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 12:15:04