我需要为 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);
};
典型的 T 是字符串、双精度、向量。
阅读文档后,我尝试对使用的每种类型使用瘦包装器。这是字符串和双精度的包装器以及相应的类声明。
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>());
它可以编译,但是当我尝试使用 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
有趣的是,当我只为双精度或字符串值公开 Foo 时,即
class_<Foo>("Foo")
.def("getValue",getValueString,
return_value_policy<copy_const_reference>())
.def("setValue",setValueString,
return_value_policy<reference_existing_object>());
它工作正常。我错过了什么吗?