embed.h
Go to the documentation of this file.
1 /*
2  pybind11/embed.h: Support for embedding the interpreter
3 
4  Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>
5 
6  All rights reserved. Use of this source code is governed by a
7  BSD-style license that can be found in the LICENSE file.
8 */
9 
10 #pragma once
11 
12 #include "pybind11.h"
13 #include "eval.h"
14 
15 #include <memory>
16 #include <vector>
17 
18 #if defined(PYPY_VERSION)
19 # error Embedding the interpreter is not supported with PyPy
20 #endif
21 
22 #define PYBIND11_EMBEDDED_MODULE_IMPL(name) \
23  extern "C" PyObject *pybind11_init_impl_##name(); \
24  extern "C" PyObject *pybind11_init_impl_##name() { return pybind11_init_wrapper_##name(); }
25 
41 #define PYBIND11_EMBEDDED_MODULE(name, variable) \
42  static ::pybind11::module_::module_def PYBIND11_CONCAT(pybind11_module_def_, name); \
43  static void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ &); \
44  static PyObject PYBIND11_CONCAT(*pybind11_init_wrapper_, name)() { \
45  auto m = ::pybind11::module_::create_extension_module( \
46  PYBIND11_TOSTRING(name), nullptr, &PYBIND11_CONCAT(pybind11_module_def_, name)); \
47  try { \
48  PYBIND11_CONCAT(pybind11_init_, name)(m); \
49  return m.ptr(); \
50  } \
51  PYBIND11_CATCH_INIT_EXCEPTIONS \
52  } \
53  PYBIND11_EMBEDDED_MODULE_IMPL(name) \
54  ::pybind11::detail::embedded_module PYBIND11_CONCAT(pybind11_module_, name)( \
55  PYBIND11_TOSTRING(name), PYBIND11_CONCAT(pybind11_init_impl_, name)); \
56  void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ \
57  & variable) // NOLINT(bugprone-macro-parentheses)
58 
61 
62 struct embedded_module {
64  using init_t = PyObject *(*) ();
65  embedded_module(const char *name, init_t init) {
66  if (Py_IsInitialized() != 0) {
67  pybind11_fail("Can't add new modules after the interpreter has been initialized");
68  }
69 
70  auto result = PyImport_AppendInittab(name, init);
71  if (result == -1) {
72  pybind11_fail("Insufficient memory to add a new module");
73  }
74  }
75 };
76 
78  void operator()(wchar_t *ptr) const {
79  // API docs: https://docs.python.org/3/c-api/sys.html#c.Py_DecodeLocale
80  PyMem_RawFree(ptr);
81  }
82 };
83 
84 inline wchar_t *widen_chars(const char *safe_arg) {
85  wchar_t *widened_arg = Py_DecodeLocale(safe_arg, nullptr);
86  return widened_arg;
87 }
88 
90 
91 
110 inline void initialize_interpreter(bool init_signal_handlers = true,
111  int argc = 0,
112  const char *const *argv = nullptr,
113  bool add_program_dir_to_path = true) {
114  if (Py_IsInitialized() != 0) {
115  pybind11_fail("The interpreter is already running");
116  }
117 
118 #if PY_VERSION_HEX < 0x030B0000
119 
120  Py_InitializeEx(init_signal_handlers ? 1 : 0);
121 
122  // Before it was special-cased in python 3.8, passing an empty or null argv
123  // caused a segfault, so we have to reimplement the special case ourselves.
124  bool special_case = (argv == nullptr || argc <= 0);
125 
126  const char *const empty_argv[]{"\0"};
127  const char *const *safe_argv = special_case ? empty_argv : argv;
128  if (special_case) {
129  argc = 1;
130  }
131 
132  auto argv_size = static_cast<size_t>(argc);
133  // SetArgv* on python 3 takes wchar_t, so we have to convert.
134  std::unique_ptr<wchar_t *[]> widened_argv(new wchar_t *[argv_size]);
135  std::vector<std::unique_ptr<wchar_t[], detail::wide_char_arg_deleter>> widened_argv_entries;
136  widened_argv_entries.reserve(argv_size);
137  for (size_t ii = 0; ii < argv_size; ++ii) {
138  widened_argv_entries.emplace_back(detail::widen_chars(safe_argv[ii]));
139  if (!widened_argv_entries.back()) {
140  // A null here indicates a character-encoding failure or the python
141  // interpreter out of memory. Give up.
142  return;
143  }
144  widened_argv[ii] = widened_argv_entries.back().get();
145  }
146 
147  auto *pysys_argv = widened_argv.get();
148 
149  PySys_SetArgvEx(argc, pysys_argv, static_cast<int>(add_program_dir_to_path));
150 #else
151  PyConfig config;
152  PyConfig_InitIsolatedConfig(&config);
153  config.install_signal_handlers = init_signal_handlers ? 1 : 0;
154 
155  PyStatus status = PyConfig_SetBytesArgv(&config, argc, const_cast<char *const *>(argv));
156  if (PyStatus_Exception(status)) {
157  // A failure here indicates a character-encoding failure or the python
158  // interpreter out of memory. Give up.
159  PyConfig_Clear(&config);
160  throw std::runtime_error(PyStatus_IsError(status) ? status.err_msg
161  : "Failed to prepare CPython");
162  }
163  status = Py_InitializeFromConfig(&config);
164  PyConfig_Clear(&config);
165  if (PyStatus_Exception(status)) {
166  throw std::runtime_error(PyStatus_IsError(status) ? status.err_msg
167  : "Failed to init CPython");
168  }
169  if (add_program_dir_to_path) {
170  PyRun_SimpleString("import sys, os.path; "
171  "sys.path.insert(0, "
172  "os.path.abspath(os.path.dirname(sys.argv[0])) "
173  "if sys.argv and os.path.exists(sys.argv[0]) else '')");
174  }
175 #endif
176 }
177 
213 inline void finalize_interpreter() {
214  handle builtins(PyEval_GetBuiltins());
215  const char *id = PYBIND11_INTERNALS_ID;
216 
217  // Get the internals pointer (without creating it if it doesn't exist). It's possible for the
218  // internals to be created during Py_Finalize() (e.g. if a py::capsule calls `get_internals()`
219  // during destruction), so we get the pointer-pointer here and check it after Py_Finalize().
220  detail::internals **internals_ptr_ptr = detail::get_internals_pp();
221  // It could also be stashed in builtins, so look there too:
222  if (builtins.contains(id) && isinstance<capsule>(builtins[id])) {
223  internals_ptr_ptr = capsule(builtins[id]);
224  }
225  // Local internals contains data managed by the current interpreter, so we must clear them to
226  // avoid undefined behaviors when initializing another interpreter
229 
230  Py_Finalize();
231 
232  if (internals_ptr_ptr) {
233  delete *internals_ptr_ptr;
234  *internals_ptr_ptr = nullptr;
235  }
236 }
237 
254 public:
255  explicit scoped_interpreter(bool init_signal_handlers = true,
256  int argc = 0,
257  const char *const *argv = nullptr,
258  bool add_program_dir_to_path = true) {
259  initialize_interpreter(init_signal_handlers, argc, argv, add_program_dir_to_path);
260  }
261 
262  scoped_interpreter(const scoped_interpreter &) = delete;
263  scoped_interpreter(scoped_interpreter &&other) noexcept { other.is_valid = false; }
264  scoped_interpreter &operator=(const scoped_interpreter &) = delete;
265  scoped_interpreter &operator=(scoped_interpreter &&) = delete;
266 
268  if (is_valid) {
270  }
271  }
272 
273 private:
274  bool is_valid = true;
275 };
276 
void initialize_interpreter(bool init_signal_handlers=true, int argc=0, const char *const *argv=nullptr, bool add_program_dir_to_path=true)
Definition: embed.h:110
PyObject *(*)() init_t
Definition: embed.h:64
embedded_module(const char *name, init_t init)
Definition: embed.h:65
scoped_interpreter(bool init_signal_handlers=true, int argc=0, const char *const *argv=nullptr, bool add_program_dir_to_path=true)
Definition: embed.h:255
void finalize_interpreter()
Definition: embed.h:213
wchar_t * widen_chars(const char *safe_arg)
Definition: embed.h:84
std::forward_list< ExceptionTranslator > registered_exception_translators
Definition: internals.h:477
scoped_interpreter(scoped_interpreter &&other) noexcept
Definition: embed.h:263
static const Similarity3 id
PyExc_RuntimeError [[noreturn]] PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Used internally.
Values result
Python 2.7/3.x compatible version of PyImport_AppendInittab and error checks.
Definition: embed.h:63
local_internals & get_local_internals()
Works like get_internals, but for things which are locally registered.
Definition: internals.h:514
type_map< type_info * > registered_types_cpp
Definition: internals.h:476
#define PYBIND11_INTERNALS_ID
Definition: internals.h:280
Annotation for function names.
Definition: attr.h:48
void operator()(wchar_t *ptr) const
Definition: embed.h:78
internals **& get_internals_pp()
Definition: internals.h:292
#define PYBIND11_NAMESPACE_END(name)
#define PYBIND11_NAMESPACE_BEGIN(name)


gtsam
Author(s):
autogenerated on Tue Jul 4 2023 02:34:12