将Python函数传递给Boost C ++ [英] Passing Python function to Boost C++

查看:208
本文介绍了将Python函数传递给Boost C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解Boost功能。我想传递一个Python函数到使用Boost Python包装的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);
}

当我尝试编译这个错误时, $ c> setOperator 函数说不能将'boost :: python :: api :: object'转换为'double'in return 。如果我用 typedef void(op_t)(double); 替换typedef行并更改 callOperator 返回void。这允许我传递可以操作参数但不返回任何东西的Python函数。

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.

我的代码有什么问题?我应该如何纠正它传递一个返回值的Python函数?

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

推荐答案

经过大量的搜索和一些试验,错误,我设法修改我的代码,使其工作。我不得不为Boost Python对象创建一个包装器结构,它包括一个 operator()方法,以便包装的对象在被赋值之前可以被转换为Boost函数到 op 变量。下面是修改后的代码:

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) );
}



我按照类似于这篇文章。但是,我仍然不明白为什么不返回void的函数需要这样的包装/转换。

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.

这篇关于将Python函数传递给Boost C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆