title: embedding Python in C++ using pybind11, Segmentation fault
body: <p>I'm trying to <em>embed</em> Python in C++ using pybind11. Embedding got a lot less attention than <em>extension</em>, and useful resources are hard to find.</p>
  
  <p>Here's my naive code</p>
  
  <pre><code>#include "Python.h"
  #include "pybind11/pybind11.h"
  
  #include &lt;iostream&gt;
  
  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 &lt;&lt; "sqrt(36.0) = " &lt;&lt; v.cast&lt;double&gt;() &lt;&lt; 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;
  }
  </code></pre>
  
  <p>Without the <code>kwargs</code> line, everything looked fine. With it, I got set-fault.</p>
  
  <p>One wild guess is that I need to somehow <em>delete</em> or <em>decref</em> <code>kwargs</code>, which was not used by Python.</p>
  
  <p>Any pointers are appreciated.</p>