boost::python PyObject implicit cast

191 Views Asked by At

I have C++ classes that handle callbacks for both C++ and python. for instance:

typedef void (*SomeCppCallback)(int count);

class Callback {
    public:
        Callback(PyObject* callable); 
        Callback(SomeCppCallback callable);
}

And some APIs use it, for instance:

void Foo(Callback) {
    // doing something
}

BOOST_PYTHON_MODULE(libexample_project) {
    class_<Callback>("Callback", init<PyObject*>());

    def("Foo", Foo);
}

I want that in the python side calling for Foo with a callback will be implicitly cast into Callback, but it doesn't work - the code is something like

import libexample_project

def PrintMe(number):
    print "I am", number 

libexample_project.Foo(PrintMe)

And I got errors such:

Boost.Python.ArgumentError: Python argument types in
    Foo(function)
did not match C++ signature:
    Foo(Callback)

I tried to use implicitly_convertible:

BOOST_PYTHON_MODULE(libexample_project) {
    class_<Callback>("Callback", init<PyObject*>());

    implicitly_convertible<PyObject*, Callback>();

    def("Foo", Foo);
}

But in vain.

Any suggestions?

0

There are 0 best solutions below