python - 如何在 pybind11 中将 python 函数转换/转换为 std::function<double(double*)> ?

标签 python c++11 pybind11

我正在使用 pybind11 为我的 C++ 项目实现绑定(bind)。 所以,我的问题基本上是如何在解释器中定义 python 函数 并从 C++ 代码中调用它。 C++ 接口(interface)使用指针 (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 *)> &func : std::array 是 const,因此它的 .data() 返回一个 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

关于python - 如何在 pybind11 中将 python 函数转换/转换为 std::function<double(double*)> ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45459292/

相关文章:

python - 为什么我不能让我的静态目录与 django 1.3 一起工作?

c++ - 重置 move 对象的常用惯用法是什么?

python - 将嵌入式 python asyncio 集成到 boost::asio 事件循环中

python - 如何使用 pybind11 绑定(bind)一个以 numpy.array() 作为参数的函数,例如形状 (10, 10, 3)?

python - 使用 pybind11 或 Python C API 编译和执行 AST

python - 如何在没有网络浏览器的情况下使用 google drive API

python - 从字典的元素创建 Pandas 数据框

python - 洗牌的程序

c++ - 使 mongo-cxx-driver 找不到包括

c++11 - 在 vector::emplace_back 中就地构造 std::pair