Search code examples
c++boost-pythonboost-bindboost-function

Boost.Bind with Function and Python


I get some compile time errors and I can't understand why that is. The following code will refuse to compile, giving me the following errors:

error C2664: 'void (PyObject *,const char *,boost::type *)' : cannot convert parameter 1 from 'const char *' to 'PyObject *'
error C2664: 'void (PyObject *,const char *,boost::type *)' : cannot convert parameter 3 from 'boost::shared_ptr' to 'boost::type *'

PyObject* self = ...;
const char* fname = "...";
boost::function<void (boost::shared_ptr<Event>)> func;
func = boost::bind(boost::python::call_method<void>, self, fname, _1);

Solution

  • boost::python::call_method consists of several overloaded functions that take a different number of arguments, defined like this:

    template <class R>
    R call_method(PyObject* self, char const* method);
    template <class R, class A1>
    R call_method(PyObject* self, char const* method, A1 const&);
    template <class R, class A1, class A2>
    R call_method(PyObject* self, char const* method, A1 const&, A2 const&);
    ...
    

    When you call it directly (e.g. call_method<void>(self, name, arg1, arg2)), the compiler can choose the correct overload and templated argument types automatically. But when you pass a function pointer to call_method into bind, you need to manually specify the overload and argument types, by using:

    call_method<ReturnType, Arg1Type, Arg2Type, ...>
    

    Or in this case:

    call_method<void, boost::shared_ptr<Event> >