[英]pybind11 basic callback, incompatible function signature error
我一生无法获得一个非常基本的Python回调函数在pybind11构建的扩展模块中工作。 我正在尝试遵循此处的示例,但我想我一定是误会了一些东西。
C ++代码如下:
#include <iostream>
#include <functional>
#include <pybind11/pybind11.h>
namespace py = pybind11;
void run_test(const std::function<int(int)>& f)
{
// Call python function?
int r = f(5);
std::cout << "result: " << r << std::endl;
}
PYBIND11_PLUGIN(mymodule)
{
py::module m("mymodule");
m.def("run_test", &run_test);
return m.ptr();
}
使用此模块的Python代码是
import mymodule as mm
# Test function
def test(x):
return 2*x
mm.run_test(test)
但是我得到这个错误:
Traceback (most recent call last):
File "test.py", line 7, in <module>
mm.run_test(test)
TypeError: run_test(): incompatible function arguments. The following argument types are supported:
1. (arg0: std::function<int (int)>) -> None
Invoked with: <function test at 0x2b506b282c80>
为什么它认为功能签名不匹配? 我试图匹配这些示例,但我想我必须误解了一些...
好的,我误解了为什么在该示例中使用了std :: function。 那是为了进行更复杂的两次回调,在此过程中,将C ++函数传递给Python,然后又传递回C ++,以检查它在整个过程中是否还存在。 对于刚刚调用Python函数一个需要使用py::object
和把结果到C ++型(如所描述的在这里 ):
void run_test(const py::object& f)
{
// Call python function?
py::object pyr = f(5);
int r = pyr.cast<int>();
std::cout << "result: " << r << std::endl;
}
我相信您的问题是您忘记了#include <pybind11/functional.h>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.