我一辈子都无法在使用 pybind11 构建的扩展模块中获得一个非常基本的 Python 回调函数。我试图按照这里的例子,但我想我一定是误解了一些东西。
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>
为什么它认为函数签名不匹配?我试图匹配这些例子,但我想我一定误解了一些东西......