c++ - Boost python包装了一个虚拟方法

标签 c++ python boost-python virtual-functions

我正在使用 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);
};

最佳答案

  1. 您引用的关于虚函数的文档与包装虚函数有关,这些虚函数可以在 python 中进一步覆盖——即在派生自 c++ 类的 python 类中。逻辑是这样的,c++ 只处理 c++ 中的虚拟解析;如果它位于包装器类(你的 python 类从中派生),this->get_override(..)将进一步查看 python 类是否覆盖了该特定函数。

    尚不清楚这是否真的是您所需要的(即从 C++ 类派生 Python 类)。如果您只想公开常规的 C++ 虚函数,则会自动处理虚解析。

  2. 此外,我不明白你们的函数需要什么样的数据。你能举一个更具体的例子吗?如果您已经有要在 c++ 类中迭代的数据,请定义特殊的 python 函数 __iter__ ,它将返回一个代理迭代器对象(您在 c++ 中定义迭代器类并将其包装在 python 中);此代理迭代器必须保持内部迭代状态并定义 __iter__ (返回 self ),next (返回下一个容器项目),并在最后引发 StopIteraton。这就是 python 迭代协议(protocol),所有常用构造(for 等)都将自动运行。 (参见例如 here,迭代器类 here 的例子)

  3. (备注)不通过vector<int>作为参数,避免使用 const vector<int>& 进行复制. vector<int> 的转换器来自 python(如果你定义它们)将工作得很好。

关于c++ - Boost python包装了一个虚拟方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6668670/

相关文章:

c++ - 停止代码块编译器并返回值

c++ - 如何编写函数和成员函数的包装器,在包装函数之前和之后执行一些代码?

c++ - “卸载”Python 模块和 'unbinding' 关联的 API

c++ - 模仿C++中的fortran print and write语法

c++ - 增加音频设备的输出增益

python - 删除 Tkinter 中的最小化/最大化按钮

python - Django 模型元类的标准文档字符串是什么?

python - 具有 orm 关系的最小/最大

python - 使用 Homebrew 在 Mac OS X 上构建 python-boost hello world - Makefile vs. Resolution

c++ - 球从特定角度穿过 Racket