I'm trying to embed Python in C++ using pybind11. Embedding got a lot less attention than extension, and useful resources are hard to find.
Here's my naive code
#include "Python.h"
#include "pybind11/pybind11.h"
#include <iostream>
namespace py = pybind11;
void lock_python(PyThreadState* s)
{
PyEval_RestoreThread(s);
}
PyThreadState* unlock_python()
{
return PyEval_SaveThread();
}
void run(PyThreadState * _py_thread_state)
{
if (_py_thread_state) {
lock_python(_py_thread_state);
}
py::object np = py::module::import("numpy");
auto v = np.attr("sqrt")(py::cast(36.0));
std::cout << "sqrt(36.0) = " << v.cast<double>() << std::endl;
py::dict kwargs = py::dict(py::arg("a") = 3);
if (_py_thread_state) {
_py_thread_state = unlock_python();
}
}
int main()
{
Py_Initialize();
PyEval_InitThreads();
PyThreadState * _py_thread_state = unlock_python();
run(_py_thread_state);
if (_py_thread_state) {
lock_python(_py_thread_state);
delete _py_thread_state;
}
return 0;
}
Without the kwargs
line, everything looked fine. With it, I got set-fault.
One wild guess is that I need to somehow delete or decref kwargs
, which was not used by Python.
Any pointers are appreciated.