Lou*_*fre 9 c++ python boost boost-python
我需要为C++代码库构建python绑定.我使用boost :: python并且在尝试使用和返回模板公开包含函数的类时遇到了问题.这是一个典型的例子
class Foo
{
public:
Foo();
template<typename T> Foo& setValue(
const string& propertyName, const T& value);
template<typename T> const T& getValue(
const string& propertyName);
};
Run Code Online (Sandbox Code Playgroud)
典型的T是字符串,双,矢量.
阅读完文档后,我尝试使用所有类型的薄包装器.这是string和double的包装器以及相应的类声明.
Foo & (Foo::*setValueDouble)(const std::string&,const double &) =
&Foo::setValue;
const double & (Foo::*getValueDouble)(const std::string&) =
&Foo::getValue;
Foo & (Foo::*setValueString)(const std::string&,const std::string &) =
&Foo::setValue;
const std::string & (Foo::*getValueString)(const std::string&) =
&Foo::getValue;
class_<Foo>("Foo")
.def("setValue",setValueDouble,
return_value_policy<reference_existing_object>())
.def("getValue",getValueDouble,
return_value_policy<copy_const_reference>())
.def("getValue",getValueString,
return_value_policy<copy_const_reference>())
.def("setValue",setValueString,
return_value_policy<reference_existing_object>());
Run Code Online (Sandbox Code Playgroud)
它编译好,但是当我尝试使用python绑定时,我得到了一个C++异常.
>>> f = Foo()
>>> f.setValue("key",1.0)
>>> f.getValue("key")
Traceback (most recent call last):
File "<stdin>", line 1, in ?
RuntimeError: unidentifiable C++ exception
Run Code Online (Sandbox Code Playgroud)
有趣的是,当我只将Foo暴露给双倍或字符串值时,即
class_<Foo>("Foo")
.def("getValue",getValueString,
return_value_policy<copy_const_reference>())
.def("setValue",setValueString,
return_value_policy<reference_existing_object>());
Run Code Online (Sandbox Code Playgroud)
它工作正常.我错过了什么吗?
这可能与您的问题没有直接关系,但我不相信使用这样的模板进行函数签名转换。我会这样包装它:
class_<Foo>("Foo")
.def("setValue", &Foo::setValue<double>,
return_value_policy<reference_existing_object>())
.def("getValue", &Foo::getValue<double>,
return_value_policy<copy_const_reference>())
.def("getValue", &Foo::getValue<std::string>,
return_value_policy<copy_const_reference>())
.def("setValue", &Foo::setValue<std::string>,
return_value_policy<reference_existing_object>());
Run Code Online (Sandbox Code Playgroud)
如果这不起作用,您可能需要创建一些填充函数:
Foo& setValueDouble(foo& self, const string& propertyName, const double value)
{
return self.setValue(propertyName, value)
}
...
Run Code Online (Sandbox Code Playgroud)
并将它们导出为成员函数。
在 Boost::Python 中将多个函数重载导出到同一个名称是完全有效的,所以我认为这不是问题所在。