embed.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. #include <memory>
  11. #include <vector>
  12. #if defined(PYPY_VERSION)
  13. # error Embedding the interpreter is not supported with PyPy
  14. #endif
  15. #define PYBIND11_EMBEDDED_MODULE_IMPL(name) \
  16. extern "C" PyObject *pybind11_init_impl_##name(); \
  17. extern "C" PyObject *pybind11_init_impl_##name() { return pybind11_init_wrapper_##name(); }
  18. /** \rst
  19. Add a new module to the table of builtins for the interpreter. Must be
  20. defined in global scope. The first macro parameter is the name of the
  21. module (without quotes). The second parameter is the variable which will
  22. be used as the interface to add functions and classes to the module.
  23. .. code-block:: cpp
  24. PYBIND11_EMBEDDED_MODULE(example, m) {
  25. // ... initialize functions and classes here
  26. m.def("foo", []() {
  27. return "Hello, World!";
  28. });
  29. }
  30. \endrst */
  31. #define PYBIND11_EMBEDDED_MODULE(name, variable) \
  32. static ::pybind11::module_::module_def PYBIND11_CONCAT(pybind11_module_def_, name); \
  33. static void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ &); \
  34. static PyObject PYBIND11_CONCAT(*pybind11_init_wrapper_, name)() { \
  35. auto m = ::pybind11::module_::create_extension_module( \
  36. PYBIND11_TOSTRING(name), nullptr, &PYBIND11_CONCAT(pybind11_module_def_, name)); \
  37. try { \
  38. PYBIND11_CONCAT(pybind11_init_, name)(m); \
  39. return m.ptr(); \
  40. } \
  41. PYBIND11_CATCH_INIT_EXCEPTIONS \
  42. } \
  43. PYBIND11_EMBEDDED_MODULE_IMPL(name) \
  44. ::pybind11::detail::embedded_module PYBIND11_CONCAT(pybind11_module_, name)( \
  45. PYBIND11_TOSTRING(name), PYBIND11_CONCAT(pybind11_init_impl_, name)); \
  46. void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ \
  47. & variable) // NOLINT(bugprone-macro-parentheses)
  48. PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
  49. PYBIND11_NAMESPACE_BEGIN(detail)
  50. /// Python 2.7/3.x compatible version of `PyImport_AppendInittab` and error checks.
  51. struct embedded_module {
  52. using init_t = PyObject *(*) ();
  53. embedded_module(const char *name, init_t init) {
  54. if (Py_IsInitialized() != 0) {
  55. pybind11_fail("Can't add new modules after the interpreter has been initialized");
  56. }
  57. auto result = PyImport_AppendInittab(name, init);
  58. if (result == -1) {
  59. pybind11_fail("Insufficient memory to add a new module");
  60. }
  61. }
  62. };
  63. struct wide_char_arg_deleter {
  64. void operator()(wchar_t *ptr) const {
  65. // API docs: https://docs.python.org/3/c-api/sys.html#c.Py_DecodeLocale
  66. PyMem_RawFree(ptr);
  67. }
  68. };
  69. inline wchar_t *widen_chars(const char *safe_arg) {
  70. wchar_t *widened_arg = Py_DecodeLocale(safe_arg, nullptr);
  71. return widened_arg;
  72. }
  73. PYBIND11_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 `init_signal_handlers` parameter can be used to skip the registration of
  78. signal handlers (see the `Python documentation`_ for details). Calling this function
  79. again after the interpreter 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. The remaining optional parameters, `argc`, `argv`, and `add_program_dir_to_path` are
  84. used to populate ``sys.argv`` and ``sys.path``.
  85. See the |PySys_SetArgvEx documentation|_ for details.
  86. .. _Python documentation: https://docs.python.org/3/c-api/init.html#c.Py_InitializeEx
  87. .. |PySys_SetArgvEx documentation| replace:: ``PySys_SetArgvEx`` documentation
  88. .. _PySys_SetArgvEx documentation: https://docs.python.org/3/c-api/init.html#c.PySys_SetArgvEx
  89. \endrst */
  90. inline void initialize_interpreter(bool init_signal_handlers = true,
  91. int argc = 0,
  92. const char *const *argv = nullptr,
  93. bool add_program_dir_to_path = true) {
  94. if (Py_IsInitialized() != 0) {
  95. pybind11_fail("The interpreter is already running");
  96. }
  97. #if PY_VERSION_HEX < 0x030B0000
  98. Py_InitializeEx(init_signal_handlers ? 1 : 0);
  99. // Before it was special-cased in python 3.8, passing an empty or null argv
  100. // caused a segfault, so we have to reimplement the special case ourselves.
  101. bool special_case = (argv == nullptr || argc <= 0);
  102. const char *const empty_argv[]{"\0"};
  103. const char *const *safe_argv = special_case ? empty_argv : argv;
  104. if (special_case) {
  105. argc = 1;
  106. }
  107. auto argv_size = static_cast<size_t>(argc);
  108. // SetArgv* on python 3 takes wchar_t, so we have to convert.
  109. std::unique_ptr<wchar_t *[]> widened_argv(new wchar_t *[argv_size]);
  110. std::vector<std::unique_ptr<wchar_t[], detail::wide_char_arg_deleter>> widened_argv_entries;
  111. widened_argv_entries.reserve(argv_size);
  112. for (size_t ii = 0; ii < argv_size; ++ii) {
  113. widened_argv_entries.emplace_back(detail::widen_chars(safe_argv[ii]));
  114. if (!widened_argv_entries.back()) {
  115. // A null here indicates a character-encoding failure or the python
  116. // interpreter out of memory. Give up.
  117. return;
  118. }
  119. widened_argv[ii] = widened_argv_entries.back().get();
  120. }
  121. auto *pysys_argv = widened_argv.get();
  122. PySys_SetArgvEx(argc, pysys_argv, static_cast<int>(add_program_dir_to_path));
  123. #else
  124. PyConfig config;
  125. PyConfig_InitIsolatedConfig(&config);
  126. config.isolated = 0;
  127. config.use_environment = 1;
  128. config.install_signal_handlers = init_signal_handlers ? 1 : 0;
  129. PyStatus status = PyConfig_SetBytesArgv(&config, argc, const_cast<char *const *>(argv));
  130. if (PyStatus_Exception(status)) {
  131. // A failure here indicates a character-encoding failure or the python
  132. // interpreter out of memory. Give up.
  133. PyConfig_Clear(&config);
  134. throw std::runtime_error(PyStatus_IsError(status) ? status.err_msg
  135. : "Failed to prepare CPython");
  136. }
  137. status = Py_InitializeFromConfig(&config);
  138. PyConfig_Clear(&config);
  139. if (PyStatus_Exception(status)) {
  140. throw std::runtime_error(PyStatus_IsError(status) ? status.err_msg
  141. : "Failed to init CPython");
  142. }
  143. if (add_program_dir_to_path) {
  144. PyRun_SimpleString("import sys, os.path; "
  145. "sys.path.insert(0, "
  146. "os.path.abspath(os.path.dirname(sys.argv[0])) "
  147. "if sys.argv and os.path.exists(sys.argv[0]) else '')");
  148. }
  149. #endif
  150. }
  151. /** \rst
  152. Shut down the Python interpreter. No pybind11 or CPython API functions can be called
  153. after this. In addition, pybind11 objects must not outlive the interpreter:
  154. .. code-block:: cpp
  155. { // BAD
  156. py::initialize_interpreter();
  157. auto hello = py::str("Hello, World!");
  158. py::finalize_interpreter();
  159. } // <-- BOOM, hello's destructor is called after interpreter shutdown
  160. { // GOOD
  161. py::initialize_interpreter();
  162. { // scoped
  163. auto hello = py::str("Hello, World!");
  164. } // <-- OK, hello is cleaned up properly
  165. py::finalize_interpreter();
  166. }
  167. { // BETTER
  168. py::scoped_interpreter guard{};
  169. auto hello = py::str("Hello, World!");
  170. }
  171. .. warning::
  172. The interpreter can be restarted by calling `initialize_interpreter` again.
  173. Modules created using pybind11 can be safely re-initialized. However, Python
  174. itself cannot completely unload binary extension modules and there are several
  175. caveats with regard to interpreter restarting. All the details can be found
  176. in the CPython documentation. In short, not all interpreter memory may be
  177. freed, either due to reference cycles or user-created global data.
  178. \endrst */
  179. inline void finalize_interpreter() {
  180. handle builtins(PyEval_GetBuiltins());
  181. const char *id = PYBIND11_INTERNALS_ID;
  182. // Get the internals pointer (without creating it if it doesn't exist). It's possible for the
  183. // internals to be created during Py_Finalize() (e.g. if a py::capsule calls `get_internals()`
  184. // during destruction), so we get the pointer-pointer here and check it after Py_Finalize().
  185. detail::internals **internals_ptr_ptr = detail::get_internals_pp();
  186. // It could also be stashed in builtins, so look there too:
  187. if (builtins.contains(id) && isinstance<capsule>(builtins[id])) {
  188. internals_ptr_ptr = capsule(builtins[id]);
  189. }
  190. // Local internals contains data managed by the current interpreter, so we must clear them to
  191. // avoid undefined behaviors when initializing another interpreter
  192. detail::get_local_internals().registered_types_cpp.clear();
  193. detail::get_local_internals().registered_exception_translators.clear();
  194. Py_Finalize();
  195. if (internals_ptr_ptr) {
  196. delete *internals_ptr_ptr;
  197. *internals_ptr_ptr = nullptr;
  198. }
  199. }
  200. /** \rst
  201. Scope guard version of `initialize_interpreter` and `finalize_interpreter`.
  202. This a move-only guard and only a single instance can exist.
  203. See `initialize_interpreter` for a discussion of its constructor arguments.
  204. .. code-block:: cpp
  205. #include <pybind11/embed.h>
  206. int main() {
  207. py::scoped_interpreter guard{};
  208. py::print(Hello, World!);
  209. } // <-- interpreter shutdown
  210. \endrst */
  211. class scoped_interpreter {
  212. public:
  213. explicit scoped_interpreter(bool init_signal_handlers = true,
  214. int argc = 0,
  215. const char *const *argv = nullptr,
  216. bool add_program_dir_to_path = true) {
  217. initialize_interpreter(init_signal_handlers, argc, argv, add_program_dir_to_path);
  218. }
  219. scoped_interpreter(const scoped_interpreter &) = delete;
  220. scoped_interpreter(scoped_interpreter &&other) noexcept { other.is_valid = false; }
  221. scoped_interpreter &operator=(const scoped_interpreter &) = delete;
  222. scoped_interpreter &operator=(scoped_interpreter &&) = delete;
  223. ~scoped_interpreter() {
  224. if (is_valid) {
  225. finalize_interpreter();
  226. }
  227. }
  228. private:
  229. bool is_valid = true;
  230. };
  231. PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)