【发布时间】:2011-09-01 06:16:07
【问题描述】:
我有一个 C++ 类,它的成员函数可以接受从小到大的参数。让我们将这些参数命名为 a-f。所有参数都有默认值。作为我正在处理的 python 项目的一部分,我想将这个类公开给 python。目前,成员函数看起来像这样:
class myClass {
public:
// Constructors - set a-f to default values.
void SetParameters(std::map<std::string, double> &);
private:
double a, b, c, d, e, f;
}
void myClass::SetParameters(std::map<std::string, double> const& params) {
// Code to iterate over the map, and set any found key/value pairs to their
// corresponding variable. i.e.- "a" --> 2.0, would set myClass::a to 2.0
}
理想情况下,在 Python 中,我想使用 dict 来完成此操作:
>>> A = myModule.myClass();
>>> A.SetParameters({'a': 2.2, 'd': 4.3, b: '9.3'})
这样,用户可以按任何顺序输入值,并输入任意数量的值以被覆盖。关于如何在 boost::python 中实现这一点的任何想法?在我看来,我可以通过将地图输入更改为 boost::python 对象并使用提取函数来做到这一点。但是,这需要我更改库的接口(我更愿意保留 std::map 接口,并为 python 版本提供一些中间/自动转换技术)。想法?
【问题讨论】:
标签: c++ python boost type-conversion boost-python