embed.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. #if !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)
  2. /*
  3. pybind11/embed.h: Support for embedding the interpreter
  4. Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>
  5. All rights reserved. Use of this source code is governed by a
  6. BSD-style license that can be found in the LICENSE file.
  7. */
  8. #pragma once
  9. #include "pybind11.h"
  10. #include "eval.h"
  11. #include <memory>
  12. #include <vector>
  13. #if defined(PYPY_VERSION)
  14. # error Embedding the interpreter is not supported with PyPy
  15. #endif
  16. #define PYBIND11_EMBEDDED_MODULE_IMPL(name) \
  17. extern "C" PyObject *pybind11_init_impl_##name(); \
  18. extern "C" PyObject *pybind11_init_impl_##name() { return pybind11_init_wrapper_##name(); }
  19. /** \rst
  20. Add a new module to the table of builtins for the interpreter. Must be
  21. defined in global scope. The first macro parameter is the name of the
  22. module (without quotes). The second parameter is the variable which will
  23. be used as the interface to add functions and classes to the module.
  24. .. code-block:: cpp
  25. PYBIND11_EMBEDDED_MODULE(example, m) {
  26. // ... initialize functions and classes here
  27. m.def("foo", []() {
  28. return "Hello, World!";
  29. });
  30. }
  31. The third and subsequent macro arguments are optional, and can be used to
  32. mark the module as supporting various Python features.
  33. - ``mod_gil_not_used()``
  34. - ``multiple_interpreters::per_interpreter_gil()``
  35. - ``multiple_interpreters::shared_gil()``
  36. - ``multiple_interpreters::not_supported()``
  37. .. code-block:: cpp
  38. PYBIND11_EMBEDDED_MODULE(example, m, py::mod_gil_not_used()) {
  39. m.def("foo", []() {
  40. return "Hello, Free-threaded World!";
  41. });
  42. }
  43. \endrst */
  44. PYBIND11_WARNING_PUSH
  45. PYBIND11_WARNING_DISABLE_CLANG("-Wgnu-zero-variadic-macro-arguments")
  46. #define PYBIND11_EMBEDDED_MODULE(name, variable, ...) \
  47. PYBIND11_MODULE_PYINIT(name, {}, ##__VA_ARGS__) \
  48. ::pybind11::detail::embedded_module PYBIND11_CONCAT(pybind11_module_, name)( \
  49. PYBIND11_TOSTRING(name), PYBIND11_CONCAT(PyInit_, name)); \
  50. PYBIND11_MODULE_EXEC(name, variable)
  51. PYBIND11_WARNING_POP
  52. PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
  53. PYBIND11_NAMESPACE_BEGIN(detail)
  54. /// Python 2.7/3.x compatible version of `PyImport_AppendInittab` and error checks.
  55. struct embedded_module {
  56. using init_t = PyObject *(*) ();
  57. embedded_module(const char *name, init_t init) {
  58. if (Py_IsInitialized() != 0) {
  59. pybind11_fail("Can't add new modules after the interpreter has been initialized");
  60. }
  61. auto result = PyImport_AppendInittab(name, init);
  62. if (result == -1) {
  63. pybind11_fail("Insufficient memory to add a new module");
  64. }
  65. }
  66. };
  67. struct wide_char_arg_deleter {
  68. void operator()(wchar_t *ptr) const {
  69. // API docs: https://docs.python.org/3/c-api/sys.html#c.Py_DecodeLocale
  70. PyMem_RawFree(ptr);
  71. }
  72. };
  73. inline wchar_t *widen_chars(const char *safe_arg) {
  74. wchar_t *widened_arg = Py_DecodeLocale(safe_arg, nullptr);
  75. return widened_arg;
  76. }
  77. inline void precheck_interpreter() {
  78. if (Py_IsInitialized() != 0) {
  79. pybind11_fail("The interpreter is already running");
  80. }
  81. }
  82. #if !defined(PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX)
  83. # define PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX (0x03080000)
  84. #endif
  85. #if PY_VERSION_HEX < PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX
  86. inline void initialize_interpreter_pre_pyconfig(bool init_signal_handlers,
  87. int argc,
  88. const char *const *argv,
  89. bool add_program_dir_to_path) {
  90. detail::precheck_interpreter();
  91. Py_InitializeEx(init_signal_handlers ? 1 : 0);
  92. auto argv_size = static_cast<size_t>(argc);
  93. // SetArgv* on python 3 takes wchar_t, so we have to convert.
  94. std::unique_ptr<wchar_t *[]> widened_argv(new wchar_t *[argv_size]);
  95. std::vector<std::unique_ptr<wchar_t[], detail::wide_char_arg_deleter>> widened_argv_entries;
  96. widened_argv_entries.reserve(argv_size);
  97. for (size_t ii = 0; ii < argv_size; ++ii) {
  98. widened_argv_entries.emplace_back(detail::widen_chars(argv[ii]));
  99. if (!widened_argv_entries.back()) {
  100. // A null here indicates a character-encoding failure or the python
  101. // interpreter out of memory. Give up.
  102. return;
  103. }
  104. widened_argv[ii] = widened_argv_entries.back().get();
  105. }
  106. auto *pysys_argv = widened_argv.get();
  107. PySys_SetArgvEx(argc, pysys_argv, static_cast<int>(add_program_dir_to_path));
  108. }
  109. #endif
  110. PYBIND11_NAMESPACE_END(detail)
  111. #if PY_VERSION_HEX >= PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX
  112. inline void initialize_interpreter(PyConfig *config,
  113. int argc = 0,
  114. const char *const *argv = nullptr,
  115. bool add_program_dir_to_path = true) {
  116. detail::precheck_interpreter();
  117. PyStatus status = PyConfig_SetBytesArgv(config, argc, const_cast<char *const *>(argv));
  118. if (PyStatus_Exception(status) != 0) {
  119. // A failure here indicates a character-encoding failure or the python
  120. // interpreter out of memory. Give up.
  121. PyConfig_Clear(config);
  122. throw std::runtime_error(PyStatus_IsError(status) != 0 ? status.err_msg
  123. : "Failed to prepare CPython");
  124. }
  125. status = Py_InitializeFromConfig(config);
  126. if (PyStatus_Exception(status) != 0) {
  127. PyConfig_Clear(config);
  128. throw std::runtime_error(PyStatus_IsError(status) != 0 ? status.err_msg
  129. : "Failed to init CPython");
  130. }
  131. if (add_program_dir_to_path) {
  132. PyRun_SimpleString("import sys, os.path; "
  133. "sys.path.insert(0, "
  134. "os.path.abspath(os.path.dirname(sys.argv[0])) "
  135. "if sys.argv and os.path.exists(sys.argv[0]) else '')");
  136. }
  137. PyConfig_Clear(config);
  138. }
  139. #endif
  140. /** \rst
  141. Initialize the Python interpreter. No other pybind11 or CPython API functions can be
  142. called before this is done; with the exception of `PYBIND11_EMBEDDED_MODULE`. The
  143. optional `init_signal_handlers` parameter can be used to skip the registration of
  144. signal handlers (see the `Python documentation`_ for details). Calling this function
  145. again after the interpreter has already been initialized is a fatal error.
  146. If initializing the Python interpreter fails, then the program is terminated. (This
  147. is controlled by the CPython runtime and is an exception to pybind11's normal behavior
  148. of throwing exceptions on errors.)
  149. The remaining optional parameters, `argc`, `argv`, and `add_program_dir_to_path` are
  150. used to populate ``sys.argv`` and ``sys.path``.
  151. See the |PySys_SetArgvEx documentation|_ for details.
  152. .. _Python documentation: https://docs.python.org/3/c-api/init.html#c.Py_InitializeEx
  153. .. |PySys_SetArgvEx documentation| replace:: ``PySys_SetArgvEx`` documentation
  154. .. _PySys_SetArgvEx documentation: https://docs.python.org/3/c-api/init.html#c.PySys_SetArgvEx
  155. \endrst */
  156. inline void initialize_interpreter(bool init_signal_handlers = true,
  157. int argc = 0,
  158. const char *const *argv = nullptr,
  159. bool add_program_dir_to_path = true) {
  160. #if PY_VERSION_HEX < PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX
  161. detail::initialize_interpreter_pre_pyconfig(
  162. init_signal_handlers, argc, argv, add_program_dir_to_path);
  163. #else
  164. PyConfig config;
  165. PyConfig_InitPythonConfig(&config);
  166. // See PR #4473 for background
  167. config.parse_argv = 0;
  168. config.install_signal_handlers = init_signal_handlers ? 1 : 0;
  169. initialize_interpreter(&config, argc, argv, add_program_dir_to_path);
  170. #endif
  171. // There is exactly one interpreter alive currently.
  172. detail::get_num_interpreters_seen() = 1;
  173. }
  174. /** \rst
  175. Shut down the Python interpreter. No pybind11 or CPython API functions can be called
  176. after this. In addition, pybind11 objects must not outlive the interpreter:
  177. .. code-block:: cpp
  178. { // BAD
  179. py::initialize_interpreter();
  180. auto hello = py::str("Hello, World!");
  181. py::finalize_interpreter();
  182. } // <-- BOOM, hello's destructor is called after interpreter shutdown
  183. { // GOOD
  184. py::initialize_interpreter();
  185. { // scoped
  186. auto hello = py::str("Hello, World!");
  187. } // <-- OK, hello is cleaned up properly
  188. py::finalize_interpreter();
  189. }
  190. { // BETTER
  191. py::scoped_interpreter guard{};
  192. auto hello = py::str("Hello, World!");
  193. }
  194. .. warning::
  195. The interpreter can be restarted by calling `initialize_interpreter` again.
  196. Modules created using pybind11 can be safely re-initialized. However, Python
  197. itself cannot completely unload binary extension modules and there are several
  198. caveats with regard to interpreter restarting. All the details can be found
  199. in the CPython documentation. In short, not all interpreter memory may be
  200. freed, either due to reference cycles or user-created global data.
  201. \endrst */
  202. inline void finalize_interpreter() {
  203. // get rid of any thread-local interpreter cache that currently exists
  204. if (detail::get_num_interpreters_seen() > 1) {
  205. detail::get_internals_pp_manager().unref();
  206. detail::get_local_internals_pp_manager().unref();
  207. // We know there can be no other interpreter alive now, so we can lower the count
  208. detail::get_num_interpreters_seen() = 1;
  209. }
  210. // Re-fetch the internals pointer-to-pointer (but not the internals itself, which might not
  211. // exist). It's possible for the internals to be created during Py_Finalize() (e.g. if a
  212. // py::capsule calls `get_internals()` during destruction), so we get the pointer-pointer here
  213. // and check it after Py_Finalize().
  214. detail::get_internals_pp_manager().get_pp();
  215. detail::get_local_internals_pp_manager().get_pp();
  216. Py_Finalize();
  217. detail::get_internals_pp_manager().destroy();
  218. // Local internals contains data managed by the current interpreter, so we must clear them to
  219. // avoid undefined behaviors when initializing another interpreter
  220. detail::get_local_internals_pp_manager().destroy();
  221. // We know there is no interpreter alive now, so we can reset the count
  222. detail::get_num_interpreters_seen() = 0;
  223. }
  224. /** \rst
  225. Scope guard version of `initialize_interpreter` and `finalize_interpreter`.
  226. This a move-only guard and only a single instance can exist.
  227. See `initialize_interpreter` for a discussion of its constructor arguments.
  228. .. code-block:: cpp
  229. #include <pybind11/embed.h>
  230. int main() {
  231. py::scoped_interpreter guard{};
  232. py::print(Hello, World!);
  233. } // <-- interpreter shutdown
  234. \endrst */
  235. class scoped_interpreter {
  236. public:
  237. explicit scoped_interpreter(bool init_signal_handlers = true,
  238. int argc = 0,
  239. const char *const *argv = nullptr,
  240. bool add_program_dir_to_path = true) {
  241. initialize_interpreter(init_signal_handlers, argc, argv, add_program_dir_to_path);
  242. }
  243. #if PY_VERSION_HEX >= PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX
  244. explicit scoped_interpreter(PyConfig *config,
  245. int argc = 0,
  246. const char *const *argv = nullptr,
  247. bool add_program_dir_to_path = true) {
  248. initialize_interpreter(config, argc, argv, add_program_dir_to_path);
  249. }
  250. #endif
  251. scoped_interpreter(const scoped_interpreter &) = delete;
  252. scoped_interpreter(scoped_interpreter &&other) noexcept { other.is_valid = false; }
  253. scoped_interpreter &operator=(const scoped_interpreter &) = delete;
  254. scoped_interpreter &operator=(scoped_interpreter &&) = delete;
  255. ~scoped_interpreter() {
  256. if (is_valid) {
  257. finalize_interpreter();
  258. }
  259. }
  260. private:
  261. bool is_valid = true;
  262. };
  263. PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
  264. #else
  265. #error "This file should not be included when either TORCH_STABLE_ONLY or TORCH_TARGET_VERSION is defined."
  266. #endif // !defined(TORCH_STABLE_ONLY) && !defined(TORCH_TARGET_VERSION)