Boost.Python和Boost.Function

Col*_*ett 4 c++ python boost function

我想包装一个boost::function类成员,以便它可以通过以下方式使用:

using namespace boost;
using namespace boost::python;

struct gui_button_t
{
    function<void()> on_pressed;
};

class_<gui_button_t>("GuiButton", init<>())
    .def("on_pressed", &gui_button_t::on_pressed);
Run Code Online (Sandbox Code Playgroud)

然后在Python中:

def callback_function():
    print 'button has been pressed'

button = GuiButton()
button.on_pressed = callback_function
button.on_pressed() # function should be callable from C++ or Python
Run Code Online (Sandbox Code Playgroud)

但是,尝试此操作会产生关于类模板参数等的大量错误.

我做了一些搜索,但一直找不到我一直在寻找的答案.下面的文章有点接近,但他们没有直接涉及这个主题.

http://bfroehle.com/2011/07/18/boost-python-and-boost-function-ii/

我在这做错了什么?为获得此功能所需的界面,我需要做什么?

提前谢谢了.

Bar*_*rry 5

Boost.Python只接受指向函数的指针和指向成员函数的指针.所以我们需要做的是将我们的callable转换为函数指针.这里的关键思想是

  1. 没有捕获的lambda可以转换为函数指针(通过巫术)
  2. 函数指针的解释方式与Python中的成员函数相同:第一个参数是 self

所以在你的情况下,我们需要做的是生成这个lambda:

+[](gui_button_t* self) {
    self->on_pressed();
}
Run Code Online (Sandbox Code Playgroud)

你已经可以在Boost.Python中使用它了,因为这是一个非常正常的函数指针.但是,我们需要一个适用于任何可调用成员的解决方案.为什么支持boost::function时,你可以支持什么?

我们将从@ Columboclosure_traits开始,但另外添加一种方法来拉出参数列表;

template <typename...> struct typelist { };

template <typename C, typename R, typename... Args>                        \
struct closure_traits<R (C::*) (Args... REM_CTOR var) cv>                  \
{                                                                          \
    using arity = std::integral_constant<std::size_t, sizeof...(Args) >;   \
    using is_variadic = std::integral_constant<bool, is_var>;              \
    using is_const    = std::is_const<int cv>;                             \
                                                                           \
    using result_type = R;                                                 \
                                                                           \
    template <std::size_t i>                                               \
    using arg = typename std::tuple_element<i, std::tuple<Args...>>::type; \
                                                                           \
    using args = typelist<Args...>;                                        \
};
Run Code Online (Sandbox Code Playgroud)

然后我们将为任何可调用成员编写一个包装器.由于我们的lambda可以不捕获,我们必须将callable作为模板参数:

template <typename CLS, typename F, F CLS::*callable>
class wrap { ... };
Run Code Online (Sandbox Code Playgroud)

我将使用C++ 14的auto返回类型演绎来节省一些打字.我们创建了一个顶级make_pointer()静态成员函数,它只是转发给另外获取参数的辅助成员函数.完整wrap看起来像:

template <typename CLS, typename F, F CLS::*callable>
class wrap {
public:
    static auto make_pointer() {
        return make_pointer_impl(typename closure_traits<F>::args{});
    }

private:
    template <typename... Args>
    static auto make_pointer_impl(typelist<Args...> ) {
        // here is our lambda that takes the CLS as the first argument
        // and then the rest of the callable's arguments,
        // and just calls it
        return +[](CLS* self, Args... args) {
            return (self->*callable)(args...);
        };
    }
};
Run Code Online (Sandbox Code Playgroud)

我们可以用它来包装你的按钮:

void (*f)(gui_button_t*) = wrap<gui_button_t, 
                                decltype(gui_button_t::on_pressed),
                                &gui_button_t::on_pressed
                                >::make_pointer();
Run Code Online (Sandbox Code Playgroud)

这有点冗长和重复,所以让我们做一个宏(叹息):

#define WRAP_MEM(CLS, MEM) wrap<CLS, decltype(CLS::MEM), &CLS::MEM>::make_pointer()
Run Code Online (Sandbox Code Playgroud)

所以我们得到:

void (*f)(gui_button_t*) = WRAP_MEM(gui_button_t, on_pressed);

f(some_button); // calls some_button->on_pressed()
Run Code Online (Sandbox Code Playgroud)

由于这给了我们一个指向函数的指针,我们可以直接使用普通的Boost.Python API:

class_<gui_button_t>("GuiButton", init<>())
    .def("on_pressed", WRAP_MEM(gui_button_t, on_pressed));
Run Code Online (Sandbox Code Playgroud)

演示展示函数指针到一个部件std::function和构件structoperator().


以上使您能够公开可调用的.如果你想另外能够做任务,即:

button = GuiButton()
button.on_pressed = callback_function
button.on_pressed()
Run Code Online (Sandbox Code Playgroud)

我们需要做点别的事情.你无法operator=在Python中以有意义的方式公开,所以为了支持上述功能,你必须改写__setattr__.现在,如果你愿意:

button.set_on_pressed(callback_function)
Run Code Online (Sandbox Code Playgroud)

我们可以扩展上面的wrap解决方案来添加一个setter,其实现方式如下:

static auto set_callable() {
    return make_setter_impl(
        typelist<typename closure_traits<F>::result_type>{},
        typename closure_traits<F>::args{});
}

template <typename R, typename... Args>
static auto make_setter_impl(typelist<R>, typelist<Args...> ) {
    return +[](CLS* self, py::object cb) {
        (self->*callable) = [cb](Args... args) {
            return py::extract<R>(
                cb(args...))();
        };
    };
}

// need a separate overload just for void
template <typename... Args>
static auto make_setter_impl(typelist<void>, typelist<Args...> ) {
    return +[](CLS* self, py::object cb) {
        (self->*callable) = [cb](Args... args) {
            cb(args...);
        };
    };
}

#define SET_MEM(CLS, MEM) wrap<CLS, decltype(CLS::MEM), &CLS::MEM>::set_callable()
Run Code Online (Sandbox Code Playgroud)

然后您可以通过以下方式公开:

.def("set_on_pressed", SET_MEM(button, on_pressed))
Run Code Online (Sandbox Code Playgroud)

但是,如果您坚持支持直接分配,那么您还需要额外公开类似的内容:

static void setattr(py::object obj, std::string attr, py::object val)
{
     if (attr == "on_pressed") {
         button& b = py::extract<button&>(obj);
         SET_MEM(button, on_pressed)(&b, val);
     }
     else {
         py::str attr_str(attr);
         if (PyObject_GenericSetAttr(obj.ptr(), attr_str.ptr(), val.ptr()) {
             py::throw_error_already_set();
         }
     }
}


.def("__setattr__", &button::setattr);
Run Code Online (Sandbox Code Playgroud)

这样可行,但您必须为要设置的每个仿函数添加更多个案.如果每个类只有一个类似仿函数的对象,可能不是什么大问题,甚至可以编写更高阶的函数来setattr为给定的属性名称生成类似特定的函数.但如果你有倍数,它将比简单的set_on_pressed解决方案稳步变得更糟.


如果C++ 14不可用,我们必须明确指定返回类型make_pointer.我们需要一些方便的类型特征.concat:

template <typename T1, typename T2>
struct concat;

template <typename T1, typename T2>
using concat_t = typename concat<T1, T2>::type;

template <typename... A1, typename... A2>
struct concat<typelist<A1...>, typelist<A2...>> {
    using type = typelist<A1..., A2...>;
};
Run Code Online (Sandbox Code Playgroud)

然后将返回类型typelist转换为函数指针:

template <typename R, typename T>
struct make_fn_ptr;

template <typename R, typename... Args>
struct make_fn_ptr<R, typelist<Args...>> {
    using type = R(*)(Args...);
};

template <typename R, typename T>
using make_fn_ptr_t = typename make_fn_ptr<R, T>::type;
Run Code Online (Sandbox Code Playgroud)

然后在内部wrap,我们可以将结果类型定义为:

using R = make_fn_ptr_t<
                typename closure_traits<F>::result_type,
                concat_t<
                    typelist<CLS*>,
                    typename closure_traits<F>::args
                    >
                >;
Run Code Online (Sandbox Code Playgroud)

并使用它而不是auto.C++ 11演示.