gpt4 book ai didi

c++ - Boost::python 使用和返回模板公开 C++ 函数

转载 作者:太空狗 更新时间:2023-10-29 20:29:41 25 4
gpt4 key购买 nike

我需要为 C++ 代码库构建 Python 绑定(bind)。我使用 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是string, double, vector。

看完documentation ,我尝试为每种类型使用薄包装。以下是 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>());

编译正常,但是当我尝试使用 python 绑定(bind)时,出现 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

有趣的是,当我只为 double 或字符串值公开 Foo 时,即

class_<Foo>("Foo") 
.def("getValue",getValueString,
return_value_policy<copy_const_reference>())
.def("setValue",setValueString,
return_value_policy<reference_existing_object>());

它工作正常。我错过了什么吗?

最佳答案

这可能与您的问题没有直接关系,但我不相信使用这样的模板进行函数签名转换。我会这样包装它:

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>());

如果这不起作用,您可能需要创建一些 shim 函数:

Foo& setValueDouble(foo& self, const string& propertyName, const double value)
{
return self.setValue(propertyName, value)
}
...

并将它们导出为成员函数。

将多个函数重载导出到相同的名称在 Boost::Python 中是一件完全有效的事情,所以我认为这不是问题所在。

关于c++ - Boost::python 使用和返回模板公开 C++ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4844651/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com