简体   繁体   中英

Passing Python function to Boost C++

I'm trying to learn about Boost functions. I want to pass a Python function to a C++ module wrapped using Boost Python. I followed the example given here and modified it to accept functions that take an input argument and return some output. Here's my code:

typedef double (op_t)(double);
boost::function<op_t> op;

double defaultOperator(double t) {
  return t;
}

void setOperator(boost::python::object obj) {
  op = obj;
}

double callOperator(double t) {
  return op(t);
}

BOOST_PYTHON_MODULE(op1) {
  op = &defaultOperator;

  def("setOperator", &setOperator);
  def("callOperator", &callOperator);
}

When I try to compile this, I get an error in my setOperator function that says cannot convert 'boost::python::api::object' to 'double' in return . The code works if I replace the typedef line with typedef void (op_t)(double); and change callOperator to return void. This allows me to pass Python functions that can operate on arguments but do not return anything.

What is wrong in my code? How should I correct it to pass a Python function that returns a value?

After a lot of searching and some trial & error, I managed to modify my code so that it works. I had to create a wrapper struct for the Boost Python object, which included a operator() method, so that the wrapped object could then be cast as a Boost Function before being assigned to the op variable. Here's the modified code:

struct op_wrapper_t {

  op_wrapper_t( object callable ) : _callable( callable ) {}

  double operator()(double t) {
    return extract<double>(_callable(t));
  }

  object _callable;
};

void setOperator(object obj) {
  op = boost::function<double (double)>( op_wrapper_t(obj) );
}

I followed a similar procedure as the one in this post . However, I still don't understand why no such wrapper/casting is needed for functions that return void.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM