I cannot for the life of me get a very basic Python callback function to work in an extension module built with pybind11. I am trying to follow the example here , but I guess I must be misunderstanding something.
The C++ code is as follows:
#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();
}
And the Python code which uses this module is
import mymodule as mm
# Test function
def test(x):
return 2*x
mm.run_test(test)
However I get this error:
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>
Why doesn't it think the function signatures match? I tried to match the examples but I guess I must misunderstand something...
Ahh ok, I misunderstood why std::function was used in that example. That was for a more complicated double-callback, where a C++ function was passed to Python and then back into C++, to check that it survived the journey. For just calling a Python function one needs to use py::object
and cast the result to a C++ type (as described here ):
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>
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.