embed.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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. inline void precheck_interpreter() {
  74. if (Py_IsInitialized() != 0) {
  75. pybind11_fail("The interpreter is already running");
  76. }
  77. }
  78. #if !defined(PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX)
  79. # define PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX (0x03080000)
  80. #endif
  81. #if PY_VERSION_HEX < PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX
  82. inline void initialize_interpreter_pre_pyconfig(bool init_signal_handlers,
  83. int argc,
  84. const char *const *argv,
  85. bool add_program_dir_to_path) {
  86. detail::precheck_interpreter();
  87. Py_InitializeEx(init_signal_handlers ? 1 : 0);
  88. # if defined(WITH_THREAD) && PY_VERSION_HEX < 0x03070000
  89. PyEval_InitThreads();
  90. # endif
  91. // Before it was special-cased in python 3.8, passing an empty or null argv
  92. // caused a segfault, so we have to reimplement the special case ourselves.
  93. bool special_case = (argv == nullptr || argc <= 0);
  94. const char *const empty_argv[]{"\0"};
  95. const char *const *safe_argv = special_case ? empty_argv : argv;
  96. if (special_case) {
  97. argc = 1;
  98. }
  99. auto argv_size = static_cast<size_t>(argc);
  100. // SetArgv* on python 3 takes wchar_t, so we have to convert.
  101. std::unique_ptr<wchar_t *[]> widened_argv(new wchar_t *[argv_size]);
  102. std::vector<std::unique_ptr<wchar_t[], detail::wide_char_arg_deleter>> widened_argv_entries;
  103. widened_argv_entries.reserve(argv_size);
  104. for (size_t ii = 0; ii < argv_size; ++ii) {
  105. widened_argv_entries.emplace_back(detail::widen_chars(safe_argv[ii]));
  106. if (!widened_argv_entries.back()) {
  107. // A null here indicates a character-encoding failure or the python
  108. // interpreter out of memory. Give up.
  109. return;
  110. }
  111. widened_argv[ii] = widened_argv_entries.back().get();
  112. }
  113. auto *pysys_argv = widened_argv.get();
  114. PySys_SetArgvEx(argc, pysys_argv, static_cast<int>(add_program_dir_to_path));
  115. }
  116. #endif
  117. PYBIND11_NAMESPACE_END(detail)
  118. #if PY_VERSION_HEX >= PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX
  119. inline void initialize_interpreter(PyConfig *config,
  120. int argc = 0,
  121. const char *const *argv = nullptr,
  122. bool add_program_dir_to_path = true) {
  123. detail::precheck_interpreter();
  124. PyStatus status = PyConfig_SetBytesArgv(config, argc, const_cast<char *const *>(argv));
  125. if (PyStatus_Exception(status) != 0) {
  126. // A failure here indicates a character-encoding failure or the python
  127. // interpreter out of memory. Give up.
  128. PyConfig_Clear(config);
  129. throw std::runtime_error(PyStatus_IsError(status) != 0 ? status.err_msg
  130. : "Failed to prepare CPython");
  131. }
  132. status = Py_InitializeFromConfig(config);
  133. if (PyStatus_Exception(status) != 0) {
  134. PyConfig_Clear(config);
  135. throw std::runtime_error(PyStatus_IsError(status) != 0 ? status.err_msg
  136. : "Failed to init CPython");
  137. }
  138. if (add_program_dir_to_path) {
  139. PyRun_SimpleString("import sys, os.path; "
  140. "sys.path.insert(0, "
  141. "os.path.abspath(os.path.dirname(sys.argv[0])) "
  142. "if sys.argv and os.path.exists(sys.argv[0]) else '')");
  143. }
  144. PyConfig_Clear(config);
  145. }
  146. #endif
  147. /** \rst
  148. Initialize the Python interpreter. No other pybind11 or CPython API functions can be
  149. called before this is done; with the exception of `PYBIND11_EMBEDDED_MODULE`. The
  150. optional `init_signal_handlers` parameter can be used to skip the registration of
  151. signal handlers (see the `Python documentation`_ for details). Calling this function
  152. again after the interpreter has already been initialized is a fatal error.
  153. If initializing the Python interpreter fails, then the program is terminated. (This
  154. is controlled by the CPython runtime and is an exception to pybind11's normal behavior
  155. of throwing exceptions on errors.)
  156. The remaining optional parameters, `argc`, `argv`, and `add_program_dir_to_path` are
  157. used to populate ``sys.argv`` and ``sys.path``.
  158. See the |PySys_SetArgvEx documentation|_ for details.
  159. .. _Python documentation: https://docs.python.org/3/c-api/init.html#c.Py_InitializeEx
  160. .. |PySys_SetArgvEx documentation| replace:: ``PySys_SetArgvEx`` documentation
  161. .. _PySys_SetArgvEx documentation: https://docs.python.org/3/c-api/init.html#c.PySys_SetArgvEx
  162. \endrst */
  163. inline void initialize_interpreter(bool init_signal_handlers = true,
  164. int argc = 0,
  165. const char *const *argv = nullptr,
  166. bool add_program_dir_to_path = true) {
  167. #if PY_VERSION_HEX < PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX
  168. detail::initialize_interpreter_pre_pyconfig(
  169. init_signal_handlers, argc, argv, add_program_dir_to_path);
  170. #else
  171. PyConfig config;
  172. PyConfig_InitPythonConfig(&config);
  173. // See PR #4473 for background
  174. config.parse_argv = 0;
  175. config.install_signal_handlers = init_signal_handlers ? 1 : 0;
  176. initialize_interpreter(&config, argc, argv, add_program_dir_to_path);
  177. #endif
  178. }
  179. /** \rst
  180. Shut down the Python interpreter. No pybind11 or CPython API functions can be called
  181. after this. In addition, pybind11 objects must not outlive the interpreter:
  182. .. code-block:: cpp
  183. { // BAD
  184. py::initialize_interpreter();
  185. auto hello = py::str("Hello, World!");
  186. py::finalize_interpreter();
  187. } // <-- BOOM, hello's destructor is called after interpreter shutdown
  188. { // GOOD
  189. py::initialize_interpreter();
  190. { // scoped
  191. auto hello = py::str("Hello, World!");
  192. } // <-- OK, hello is cleaned up properly
  193. py::finalize_interpreter();
  194. }
  195. { // BETTER
  196. py::scoped_interpreter guard{};
  197. auto hello = py::str("Hello, World!");
  198. }
  199. .. warning::
  200. The interpreter can be restarted by calling `initialize_interpreter` again.
  201. Modules created using pybind11 can be safely re-initialized. However, Python
  202. itself cannot completely unload binary extension modules and there are several
  203. caveats with regard to interpreter restarting. All the details can be found
  204. in the CPython documentation. In short, not all interpreter memory may be
  205. freed, either due to reference cycles or user-created global data.
  206. \endrst */
  207. inline void finalize_interpreter() {
  208. // Get the internals pointer (without creating it if it doesn't exist). It's possible for the
  209. // internals to be created during Py_Finalize() (e.g. if a py::capsule calls `get_internals()`
  210. // during destruction), so we get the pointer-pointer here and check it after Py_Finalize().
  211. detail::internals **internals_ptr_ptr = detail::get_internals_pp();
  212. // It could also be stashed in state_dict, so look there too:
  213. if (object internals_obj
  214. = get_internals_obj_from_state_dict(detail::get_python_state_dict())) {
  215. internals_ptr_ptr = detail::get_internals_pp_from_capsule(internals_obj);
  216. }
  217. // Local internals contains data managed by the current interpreter, so we must clear them to
  218. // avoid undefined behaviors when initializing another interpreter
  219. detail::get_local_internals().registered_types_cpp.clear();
  220. detail::get_local_internals().registered_exception_translators.clear();
  221. Py_Finalize();
  222. if (internals_ptr_ptr) {
  223. delete *internals_ptr_ptr;
  224. *internals_ptr_ptr = nullptr;
  225. }
  226. }
  227. /** \rst
  228. Scope guard version of `initialize_interpreter` and `finalize_interpreter`.
  229. This a move-only guard and only a single instance can exist.
  230. See `initialize_interpreter` for a discussion of its constructor arguments.
  231. .. code-block:: cpp
  232. #include <pybind11/embed.h>
  233. int main() {
  234. py::scoped_interpreter guard{};
  235. py::print(Hello, World!);
  236. } // <-- interpreter shutdown
  237. \endrst */
  238. class scoped_interpreter {
  239. public:
  240. explicit scoped_interpreter(bool init_signal_handlers = true,
  241. int argc = 0,
  242. const char *const *argv = nullptr,
  243. bool add_program_dir_to_path = true) {
  244. initialize_interpreter(init_signal_handlers, argc, argv, add_program_dir_to_path);
  245. }
  246. #if PY_VERSION_HEX >= PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX
  247. explicit scoped_interpreter(PyConfig *config,
  248. int argc = 0,
  249. const char *const *argv = nullptr,
  250. bool add_program_dir_to_path = true) {
  251. initialize_interpreter(config, argc, argv, add_program_dir_to_path);
  252. }
  253. #endif
  254. scoped_interpreter(const scoped_interpreter &) = delete;
  255. scoped_interpreter(scoped_interpreter &&other) noexcept { other.is_valid = false; }
  256. scoped_interpreter &operator=(const scoped_interpreter &) = delete;
  257. scoped_interpreter &operator=(scoped_interpreter &&) = delete;
  258. ~scoped_interpreter() {
  259. if (is_valid) {
  260. finalize_interpreter();
  261. }
  262. }
  263. private:
  264. bool is_valid = true;
  265. };
  266. PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)