如何在pybind11中cast/convert一个python函数到std::function<double(double*)>?

How to cast/convert a python function to std::function<double(double*)> in pybind11?

我正在使用 pybind11 为我的 C++ 项目实现绑定。 所以,我的问题基本上是如何在解释器中定义 python 函数 并从 C++ 代码中调用它。 C++ 接口使用指针 (double*) 传递数据,我不知道如何在解释器中编写函数代码以及如何将其转换为 std::function 以执行评估:

// C++
//--------
double cpp_call( const std::array<double,N> &value, const std::function<double(double*)> &func) 
{
    return func(value.data());
}

// python binding with pybind11
// module definition... 
 ...
 m.def("py_call", &cpp_call);

//python interpreter 
//-------------------

?

拜托,有人可以给我一些提示吗?

您很可能遗漏了一些要求 header 才能使此工作正常进行,#include <pybind11/functional.h>(对于 std::function 支持)和 #include <pybind11/stl.h>(对于stl 容器支持);默认情况下 header 均未包含(以使核心项目更小)。

有了这些,您的示例几乎可以工作(它只需要将 const 添加到 std::function 的内部参数,即 const std::function<double(const double *)> &funcstd::array 是常量因此它的 .data() returns 是一个 const 指针)。

这里有一个完整的例子来展示这个工作原理:

#include <pybind11/pybind11.h>
#include <pybind11/functional.h>
#include <pybind11/stl.h>

double cpp_call(const std::array<double, 3> &values,
                const std::function<double(double *)> &func) {
    double ret = 0;
    for (auto d : values) ret += func(&d);
    return ret;
}

PYBIND11_MODULE(stack92, m) {
    m.def("sum", &cpp_call);
}

Python:

>>> import stack92
>>> def f(v): return v**.5
... 
>>> print("1+2+3 =", stack92.sum([1, 4, 9], f))
1+2+3 = 6.0