提升 Python raw_function 方法
boost python raw_function method
我想使用 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));
它不是直接包装类方法,但它比使用中间函数更干净。
相关文章:
- 为不同配置设置MSVC_RUNTIME_LIBRARY的正确方法是什么
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 使用 object 中的方法调用带有 std::bind 和 std::function.target 的 C 样式函数
- 如果子类中没有构造函数方法,则错误"no matching function for call to 'LGame::LGame(String&)'"
- 使用 gmock 匹配器将 std::function 设置为 EXPECT_CALL 中的方法参数
- 如何将对象类的方法传递为 std::function?
- 解决方法:未定义对"class::function"的引用
- 我可以在外部组装(function.asm)中制作C 方法吗?
- 如何修复空虚拟方法的"warning: no return statement in function returning non-void [-Wreturn-type]"
- C++ substr 方法 - "invalid use of ‘this’ in non-member function"
- 如何创建一个 std::function 作为方法参数,并将 std::stoi 作为默认值
- 将 boost::function 与实例方法一起使用
- 如何在谷歌测试中测试方法,使用std::function
- 在单步执行 std::function 调用时,如何跳过 std 命名空间中的方法调用?(使用 GDB
- C++ Lambda:访问 lambda 中的静态方法会导致错误'this was not captured for this lambda function'
- C++类型擦除,请使用 std::function 捕获单个类的多个方法
- 有没有什么方法可以从“std::function”返回到指针
- 实现任意类型擦除的小缓冲区优化的简单方法(如std::function.)
- 将抽象类的方法作为std::function传递
- Visual Studio 2012中的std::function目标方法