提升 Python raw_function 方法

boost python raw_function method

本文关键字:function 方法 raw Python 提升      更新时间:2023-10-16

我想使用 raw_function 公开一个类方法。像这样:

namespace py = boost::python;
class MyObject {
public:
    py::object foo(py::tuple args, py::dict kwargs) {
        // whatever
    }
};

现在,我可以使用raw_function来包装一个必须拉出self的静态函数,如下所示:

static py::object MyObject_foo(py::tuple args, py::dict kwargs) {
    MyObject& self = py::extract<MyObject&>(args[0]);
    // the docs allege that I can do args.slice(1), but that doesn't
    // compile on boost 1.55 at least, with no matching function
    // call to 'boost::python::tuple::slice(int ) const
    self.foo(py::extract<py::tuple>(args.slice(1, py::len(args))),
             kwargs);
}
py::class_<MyClass>("MyClass")
    .def("foo", py::raw_function(&MyObject_foo, 1));

这行得通,但非常冗长。我实际上有几个需要包装的原始函数,并且不希望在每个函数上都经历这个中间步骤。有没有更短的方法来包装MyObject::foo

您可以使用静态成员函数跳过额外的函数,然后以相同的方式提取self,即

namespace py = boost::python;
class MyObject {
public:
    static py::object foo(py::tuple args, py::dict kwargs)
    {
        MyObject& self = py::extract<MyObject&>(args[0]);
        // Do stuff with the self object
    }
};
py::class_<MyObject>("MyObject")
    .def("foo", py::raw_function(&MyObject::foo, 1));

它不是直接包装类方法,但它比使用中间函数更干净。

相关文章: