You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cython中能否使用C++ shared_ptr的->运算符重载?

在Cython中能否使用C++ shared_ptr的->运算符重载?

问题背景

在C++中,使用shared_ptr链式访问成员非常简洁,写法如下(所有foo、bar、abc、xyz均为shared_ptr类型):

// All foo, bar, abc, xyz are shared_ptr
foo->bar->abc->xyz

但在Cython中没有->运算符,只能通过.get()方法获取原始指针后实现链式访问,写法为:

foo.get().bar.get().abc.get().xyz

C++的shared_ptr已在头文件中定义了->运算符重载,但在Cython中使用该运算符会报错,示例代码及报错信息如下:

示例代码

from libc.stdio cimport printf

printf("%s start time: %f, finish time: %f\n",s.c_str(),
       veh->start_time, veh.get().finish_time)

报错信息

Expected ')', found '->'

回答

不能。Cython的语法体系中并未实现对C++ shared_ptr的->运算符重载的支持,必须通过.get()方法获取shared_ptr持有的原始指针,再访问其成员属性或方法。

修正后的示例代码应为:

from libc.stdio cimport printf

printf("%s start time: %f, finish time: %f\n",s.c_str(),
       veh.get().start_time, veh.get().finish_time)

如果想要简化链式访问的写法,可以考虑在Cython中为shared_ptr类型封装自定义扩展类,通过__getattr__方法自动调用.get(),不过这需要额外编写代码实现,同时要注意保障内存安全。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 02:15:58