embed.h 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. /*
  2. pybind11/embed.h: Support for embedding the interpreter
  3. Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>
  4. All rights reserved. Use of this source code is governed by a
  5. BSD-style license that can be found in the LICENSE file.
  6. */
  7. #pragma once
  8. #include "pybind11.h"
  9. #include "eval.h"
  10. #if defined(PYPY_VERSION)
  11. # error Embedding the interpreter is not supported with PyPy
  12. #endif
  13. #if PY_MAJOR_VERSION >= 3
  14. # define PYBIND11_EMBEDDED_MODULE_IMPL(name) \
  15. extern "C" PyObject *pybind11_init_impl_##name() { \
  16. return pybind11_init_wrapper_##name(); \
  17. }
  18. #else
  19. # define PYBIND11_EMBEDDED_MODULE_IMPL(name) \
  20. extern "C" void pybind11_init_impl_##name() { \
  21. pybind11_init_wrapper_##name(); \
  22. }
  23. #endif
  24. /** \rst
  25. Add a new module to the table of builtins for the interpreter. Must be
  26. defined in global scope. The first macro parameter is the name of the
  27. module (without quotes). The second parameter is the variable which will
  28. be used as the interface to add functions and classes to the module.
  29. .. code-block:: cpp
  30. PYBIND11_EMBEDDED_MODULE(example, m) {
  31. // ... initialize functions and classes here
  32. m.def("foo", []() {
  33. return "Hello, World!";
  34. });
  35. }
  36. \endrst */
  37. #define PYBIND11_EMBEDDED_MODULE(name, variable) \
  38. static void PYBIND11_CONCAT(pybind11_init_, name)(pybind11::module &); \
  39. static PyObject PYBIND11_CONCAT(*pybind11_init_wrapper_, name)() { \
  40. auto m = pybind11::module(PYBIND11_TOSTRING(name)); \
  41. try { \
  42. PYBIND11_CONCAT(pybind11_init_, name)(m); \
  43. return m.ptr(); \
  44. } catch (pybind11::error_already_set &e) { \
  45. PyErr_SetString(PyExc_ImportError, e.what()); \
  46. return nullptr; \
  47. } catch (const std::exception &e) { \
  48. PyErr_SetString(PyExc_ImportError, e.what()); \
  49. return nullptr; \
  50. } \
  51. } \
  52. PYBIND11_EMBEDDED_MODULE_IMPL(name) \
  53. pybind11::detail::embedded_module name(PYBIND11_TOSTRING(name), \
  54. PYBIND11_CONCAT(pybind11_init_impl_, name)); \
  55. void PYBIND11_CONCAT(pybind11_init_, name)(pybind11::module &variable)
  56. NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
  57. NAMESPACE_BEGIN(detail)
  58. /// Python 2.7/3.x compatible version of `PyImport_AppendInittab` and error checks.
  59. struct embedded_module {
  60. #if PY_MAJOR_VERSION >= 3
  61. using init_t = PyObject *(*)();
  62. #else
  63. using init_t = void (*)();
  64. #endif
  65. embedded_module(const char *name, init_t init) {
  66. if (Py_IsInitialized())
  67. pybind11_fail("Can't add new modules after the interpreter has been initialized");
  68. auto result = PyImport_AppendInittab(name, init);
  69. if (result == -1)
  70. pybind11_fail("Insufficient memory to add a new module");
  71. }
  72. };
  73. NAMESPACE_END(detail)
  74. /** \rst
  75. Initialize the Python interpreter. No other pybind11 or CPython API functions can be
  76. called before this is done; with the exception of `PYBIND11_EMBEDDED_MODULE`. The
  77. optional parameter can be used to skip the registration of signal handlers (see the
  78. `Python documentation`_ for details). Calling this function again after the interpreter
  79. has already been initialized is a fatal error.
  80. If initializing the Python interpreter fails, then the program is terminated. (This
  81. is controlled by the CPython runtime and is an exception to pybind11's normal behavior
  82. of throwing exceptions on errors.)
  83. .. _Python documentation: https://docs.python.org/3/c-api/init.html#c.Py_InitializeEx
  84. \endrst */
  85. inline void initialize_interpreter(bool init_signal_handlers = true) {
  86. if (Py_IsInitialized())
  87. pybind11_fail("The interpreter is already running");
  88. Py_InitializeEx(init_signal_handlers ? 1 : 0);
  89. // Make .py files in the working directory available by default
  90. module::import("sys").attr("path").cast<list>().append(".");
  91. }
  92. /** \rst
  93. Shut down the Python interpreter. No pybind11 or CPython API functions can be called
  94. after this. In addition, pybind11 objects must not outlive the interpreter:
  95. .. code-block:: cpp
  96. { // BAD
  97. py::initialize_interpreter();
  98. auto hello = py::str("Hello, World!");
  99. py::finalize_interpreter();
  100. } // <-- BOOM, hello's destructor is called after interpreter shutdown
  101. { // GOOD
  102. py::initialize_interpreter();
  103. { // scoped
  104. auto hello = py::str("Hello, World!");
  105. } // <-- OK, hello is cleaned up properly
  106. py::finalize_interpreter();
  107. }
  108. { // BETTER
  109. py::scoped_interpreter guard{};
  110. auto hello = py::str("Hello, World!");
  111. }
  112. .. warning::
  113. The interpreter can be restarted by calling `initialize_interpreter` again.
  114. Modules created using pybind11 can be safely re-initialized. However, Python
  115. itself cannot completely unload binary extension modules and there are several
  116. caveats with regard to interpreter restarting. All the details can be found
  117. in the CPython documentation. In short, not all interpreter memory may be
  118. freed, either due to reference cycles or user-created global data.
  119. \endrst */
  120. inline void finalize_interpreter() {
  121. handle builtins(PyEval_GetBuiltins());
  122. const char *id = PYBIND11_INTERNALS_ID;
  123. // Get the internals pointer (without creating it if it doesn't exist). It's possible for the
  124. // internals to be created during Py_Finalize() (e.g. if a py::capsule calls `get_internals()`
  125. // during destruction), so we get the pointer-pointer here and check it after Py_Finalize().
  126. detail::internals **internals_ptr_ptr = detail::get_internals_pp();
  127. // It could also be stashed in builtins, so look there too:
  128. if (builtins.contains(id) && isinstance<capsule>(builtins[id]))
  129. internals_ptr_ptr = capsule(builtins[id]);
  130. Py_Finalize();
  131. if (internals_ptr_ptr) {
  132. delete *internals_ptr_ptr;
  133. *internals_ptr_ptr = nullptr;
  134. }
  135. }
  136. /** \rst
  137. Scope guard version of `initialize_interpreter` and `finalize_interpreter`.
  138. This a move-only guard and only a single instance can exist.
  139. .. code-block:: cpp
  140. #include <pybind11/embed.h>
  141. int main() {
  142. py::scoped_interpreter guard{};
  143. py::print(Hello, World!);
  144. } // <-- interpreter shutdown
  145. \endrst */
  146. class scoped_interpreter {
  147. public:
  148. scoped_interpreter(bool init_signal_handlers = true) {
  149. initialize_interpreter(init_signal_handlers);
  150. }
  151. scoped_interpreter(const scoped_interpreter &) = delete;
  152. scoped_interpreter(scoped_interpreter &&other) noexcept { other.is_valid = false; }
  153. scoped_interpreter &operator=(const scoped_interpreter &) = delete;
  154. scoped_interpreter &operator=(scoped_interpreter &&) = delete;
  155. ~scoped_interpreter() {
  156. if (is_valid)
  157. finalize_interpreter();
  158. }
  159. private:
  160. bool is_valid = true;
  161. };
  162. NAMESPACE_END(PYBIND11_NAMESPACE)