我正在使用 boost python 创建到 C++ 库的绑定(bind)。这个库中的许多类都有接受 iterator/const_iterator 类型作为参数的虚方法。我并不是特别想公开这些类型,而是更愿意围绕这些接受适当容器的虚拟方法创建一些包装器。我的问题是,在“默认实现”函数中进行这种包装是否安全?
例如
class Test
{
public:
Test();
virtual ~Test();
virtual void iterate(std::vector<int>::iterator it);
};
然后用包装器类包装默认..
struct Test_wrapper: Test, boost::python::wrapper<Test>
{
.....
virtual void iterate(std::vector<int>::iterator it);
void default_iterate(std::vector<int> it)
{
Test::iterate(it.begin());
}
};
并设置与...的绑定(bind)
boost::python::class_< Test_wrapper >("Test")
.def("iterate" ,(void ( Test_wrapper::* )(std::vector<int>))(&Test_wrapper::default_iterate));
我不确定这一点,因为教程说需要将两个函数传递给“def”,但只传递一个函数似乎可行..(http://www.boost.org/doc/libs/1_43_0/libs/python/doc/tutorial/doc/html/python/exposing.html#python.class_virtual_functions)
如有任何建议,我们将不胜感激。
提前致谢,
巴巴克
编辑:
更具体地说,我正在尝试绑定(bind)一个包含方法“voxelToWorld”的类。该方法根据 vsP/end 中的点转换 wsP 中的位置。我想把这个函数包装起来,这样它的界面就更“pythonic”了,但是我不确定在保持虚拟化的同时做到这一点的正确方法。
class FieldMapping
{
public:
...
virtual void voxelToWorld(std::vector<V3d>::const_iterator vsP,
std::vector<V3d>::const_iterator end,
std::vector<V3d>::iterator wsP);
};
最佳答案
您引用的关于虚函数的文档与包装虚函数有关,这些虚函数可以在 python 中进一步覆盖——即在派生自 c++ 类的 python 类中。逻辑是这样的,c++ 只处理 c++ 中的虚拟解析;如果它位于包装器类(你的 python 类从中派生),
this->get_override(..)
将进一步查看 python 类是否覆盖了该特定函数。尚不清楚这是否真的是您所需要的(即从 C++ 类派生 Python 类)。如果您只想公开常规的 C++ 虚函数,则会自动处理虚解析。
此外,我不明白你们的函数需要什么样的数据。你能举一个更具体的例子吗?如果您已经有要在 c++ 类中迭代的数据,请定义特殊的 python 函数
__iter__
,它将返回一个代理迭代器对象(您在 c++ 中定义迭代器类并将其包装在 python 中);此代理迭代器必须保持内部迭代状态并定义__iter__
(返回 self ),next
(返回下一个容器项目),并在最后引发 StopIteraton。这就是 python 迭代协议(protocol),所有常用构造(for
等)都将自动运行。 (参见例如 here,迭代器类 here 的例子)(备注)不通过
vector<int>
作为参数,避免使用const vector<int>&
进行复制.vector<int>
的转换器来自 python(如果你定义它们)将工作得很好。
关于c++ - Boost python包装了一个虚拟方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6668670/