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

如何为Python绑定的Basilisk模块的C++属性赋值SWIG封装的std::vector<double>

问题

在macOS(Apple M1)系统上使用Basilisk航天器动力学仿真器(v2.2.1),环境为Python 3.9、SWIG 4.0.2。基于SmallBodyScience仿真搭建了bsk_rl强化学习封装,尝试为planetEphemeris.PlanetEphemeris.rightAscension属性赋值——该属性要求传入SWIG封装的std::vector<double>,但两种赋值方式均报错:

尝试的代码

代码1:

from Basilisk.simulation import planetEphemeris
self.gravBodyEphem = planetEphemeris.PlanetEphemeris()
# 尝试赋值双精度向量
self.gravBodyEphem.rightAscension = planetEphemeris.DoubleVector([0.0])

代码2:

vec = planetEphemeris.DoubleVector()
vec.push_back(0.0)
self.gravBodyEphem.rightAscension = vec

错误信息

TypeError: in method 'PlanetEphemeris_rightAscension_set', argument 2 of type 'std::vector< double,std::allocator< double > > *'

使用的是bsk_rl的旧提交版本,适配不同Basilisk版本时遇到问题,需解决如何正确将Python列表或SWIG封装的向量赋值给该SWIG暴露的C++ std::vector属性。

解决方案

错误原因是SWIG生成的setter方法期望接收指向std::vector<double>的指针,而非向量对象本身,可通过以下两种方式解决:

方法1:调用ptr()方法获取向量指针

SWIG封装的DoubleVector通常自带ptr()方法,返回底层C++对象的指针,直接将该指针赋值给属性即可:

from Basilisk.simulation import planetEphemeris
self.gravBodyEphem = planetEphemeris.PlanetEphemeris()
vec = planetEphemeris.DoubleVector([0.0])
self.gravBodyEphem.rightAscension = vec.ptr()

方法2:手动转换为指针类型

如果DoubleVector没有ptr()方法,可借助SWIG的类型转换工具手动获取指针:

from Basilisk.simulation import planetEphemeris
import swig
self.gravBodyEphem = planetEphemeris.PlanetEphemeris()
vec = planetEphemeris.DoubleVector([0.0])
# 将向量对象转换为对应指针类型
vec_ptr = swig.cast(vec, planetEphemeris.DoubleVector_ptr)
self.gravBodyEphem.rightAscension = vec_ptr

补充说明

  • 旧版本bsk_rl与Basilisk的SWIG封装特性导致部分属性setter仅接受指针参数,这是早期版本的常见设计。
  • 若需直接用Python列表赋值,需先将列表转为DoubleVector实例,再按上述方法传入指针。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 18:12:20