You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

195 lines
7.3 KiB

  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_init_##name(pybind11::module &); \
  39. static PyObject *pybind11_init_wrapper_##name() { \
  40. auto m = pybind11::module(#name); \
  41. try { \
  42. pybind11_init_##name(m); \
  43. return m.ptr(); \
  44. } catch (pybind11::error_already_set &e) { \
  45. e.clear(); \
  46. PyErr_SetString(PyExc_ImportError, e.what()); \
  47. return nullptr; \
  48. } catch (const std::exception &e) { \
  49. PyErr_SetString(PyExc_ImportError, e.what()); \
  50. return nullptr; \
  51. } \
  52. } \
  53. PYBIND11_EMBEDDED_MODULE_IMPL(name) \
  54. pybind11::detail::embedded_module name(#name, pybind11_init_impl_##name); \
  55. void pybind11_init_##name(pybind11::module &variable)
  56. NAMESPACE_BEGIN(pybind11)
  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. \endrst */
  81. inline void initialize_interpreter(bool init_signal_handlers = true) {
  82. if (Py_IsInitialized())
  83. pybind11_fail("The interpreter is already running");
  84. Py_InitializeEx(init_signal_handlers ? 1 : 0);
  85. // Make .py files in the working directory available by default
  86. auto sys_path = reinterpret_borrow<list>(module::import("sys").attr("path"));
  87. sys_path.append(".");
  88. }
  89. /** \rst
  90. Shut down the Python interpreter. No pybind11 or CPython API functions can be called
  91. after this. In addition, pybind11 objects must not outlive the interpreter:
  92. .. code-block:: cpp
  93. { // BAD
  94. py::initialize_interpreter();
  95. auto hello = py::str("Hello, World!");
  96. py::finalize_interpreter();
  97. } // <-- BOOM, hello's destructor is called after interpreter shutdown
  98. { // GOOD
  99. py::initialize_interpreter();
  100. { // scoped
  101. auto hello = py::str("Hello, World!");
  102. } // <-- OK, hello is cleaned up properly
  103. py::finalize_interpreter();
  104. }
  105. { // BETTER
  106. py::scoped_interpreter guard{};
  107. auto hello = py::str("Hello, World!");
  108. }
  109. .. warning::
  110. The interpreter can be restarted by calling `initialize_interpreter` again.
  111. Modules created using pybind11 can be safely re-initialized. However, Python
  112. itself cannot completely unload binary extension modules and there are several
  113. caveats with regard to interpreter restarting. All the details can be found
  114. in the CPython documentation. In short, not all interpreter memory may be
  115. freed, either due to reference cycles or user-created global data.
  116. \endrst */
  117. inline void finalize_interpreter() {
  118. handle builtins(PyEval_GetBuiltins());
  119. const char *id = PYBIND11_INTERNALS_ID;
  120. // Get the internals pointer (without creating it if it doesn't exist). It's possible for the
  121. // internals to be created during Py_Finalize() (e.g. if a py::capsule calls `get_internals()`
  122. // during destruction), so we get the pointer-pointer here and check it after Py_Finalize().
  123. detail::internals **internals_ptr_ptr = &detail::get_internals_ptr();
  124. // It could also be stashed in builtins, so look there too:
  125. if (builtins.contains(id) && isinstance<capsule>(builtins[id]))
  126. internals_ptr_ptr = capsule(builtins[id]);
  127. Py_Finalize();
  128. if (internals_ptr_ptr) {
  129. delete *internals_ptr_ptr;
  130. *internals_ptr_ptr = nullptr;
  131. }
  132. }
  133. /** \rst
  134. Scope guard version of `initialize_interpreter` and `finalize_interpreter`.
  135. This a move-only guard and only a single instance can exist.
  136. .. code-block:: cpp
  137. #include <pybind11/embed.h>
  138. int main() {
  139. py::scoped_interpreter guard{};
  140. py::print(Hello, World!);
  141. } // <-- interpreter shutdown
  142. \endrst */
  143. class scoped_interpreter {
  144. public:
  145. scoped_interpreter(bool init_signal_handlers = true) {
  146. initialize_interpreter(init_signal_handlers);
  147. }
  148. scoped_interpreter(const scoped_interpreter &) = delete;
  149. scoped_interpreter(scoped_interpreter &&other) noexcept { other.is_valid = false; }
  150. scoped_interpreter &operator=(const scoped_interpreter &) = delete;
  151. scoped_interpreter &operator=(scoped_interpreter &&) = delete;
  152. ~scoped_interpreter() {
  153. if (is_valid)
  154. finalize_interpreter();
  155. }
  156. private:
  157. bool is_valid = true;
  158. };
  159. NAMESPACE_END(pybind11)