boost-python原始函数方法
我想使用boost-python原始函数方法,python,c++,boost-python,Python,C++,Boost Python,我想使用raw\u函数公开一个类方法。比如: namespace py = boost::python; class MyObject { public: py::object foo(py::tuple args, py::dict kwargs) { // whatever } }; static py::object MyObject_foo(py::tuple args, py::dict kwargs) { MyObject& sel
raw\u函数
公开一个类方法。比如:
namespace py = boost::python;
class MyObject {
public:
py::object foo(py::tuple args, py::dict kwargs) {
// whatever
}
};
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));
现在,我可以使用raw_函数
包装一个静态函数,该函数必须拉出self
,如下所示:
namespace py = boost::python;
class MyObject {
public:
py::object foo(py::tuple args, py::dict kwargs) {
// whatever
}
};
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));
static py::object MyObject\u foo(py::tuple args,py::dict kwargs){
MyObject&self=py::extract(args[0]);
//文档声称我可以做args.slice(1),但事实并非如此
//至少在boost 1.55上编译,没有匹配函数
//调用“boost::python::tuple::slice(int)const”
self.foo(py::extract(args.slice(1,py::len(args)),
kwargs);
}
py::class_uuz(“MyClass”)
.def(“foo”,py::raw_函数(&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));
namespace py=boost::python;
类MyObject{
公众:
静态py::object foo(py::tuple args,py::dict kwargs)
{
MyObject&self=py::extract(args[0]);
//用self对象做一些事情
}
};
py::类_u3;(“MyObject”)
.def(“foo”,py::raw_函数(&MyObject::foo,1));
它不是直接包装类方法,但比使用中间函数更简洁。解决了我的问题,但这仍然是“在类内”。谢谢