user815129
user815129

Reputation: 2314

python function as parameter to c++ exposed class using ::boost::python

Ive been working with Python and C++ together for some time, but never tried to implement what follows:

Id like the python user to be able to write something like:

def foo(a,b):
    return a+b

myclass.myfunc(foo)

where myclass is a c++ class exposed to python with Boost.Python, with one of its methods (myfunc) that takes a function with:

int func(int,int)

signature, and only that.

Is this possible?

Im thinking about declaring:

myclass::myfunc(boost::python::object)

and extracting the typedef'ed function signature, but im just guessing..

maybe there's a better/feasible way to do this, maybe with some 'function' object?

Upvotes: 3

Views: 1521

Answers (1)

Paul Manta
Paul Manta

Reputation: 31567

You pretty much guessed the answer. Python functions are indeed just boost::python::object instances. You can then just have a boost::function<int (int, int)> and put the Python object inside that.

I just installed my OS and I don't have Boost yet, so I can't test it, but I think it will work if you just do this (without any wrapper functions):

void function(boost::function<int (int, int)> func) {
    // ...
}

// And then you expose the function as you normally would

I expect the above to work; if it doesn't this surely will:

void function_wrap(boost::python::object func)
{
    auto lambda = [func](int a, int b) -> int {
        return boost::python::extract<int>(func(a, b));
    };
    function(boost::function<int (int, int)>(lambda));
}

// And then you expose the wrapper, not the original function

Upvotes: 3

Related Questions