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 
89 inline void precheck_interpreter() {
90  if (Py_IsInitialized() != 0) {
91  pybind11_fail("The interpreter is already running");
92  }
93 }
94 
95 #if !defined(PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX)
96 # define PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX (0x03080000)
97 #endif
98 
99 #if PY_VERSION_HEX < PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX
100 inline void initialize_interpreter_pre_pyconfig(bool init_signal_handlers,
101  int argc,
102  const char *const *argv,
103  bool add_program_dir_to_path) {
105  Py_InitializeEx(init_signal_handlers ? 1 : 0);
106 # if defined(WITH_THREAD) && PY_VERSION_HEX < 0x03070000
107  PyEval_InitThreads();
108 # endif
109 
110  // Before it was special-cased in python 3.8, passing an empty or null argv
111  // caused a segfault, so we have to reimplement the special case ourselves.
112  bool special_case = (argv == nullptr || argc <= 0);
113 
114  const char *const empty_argv[]{"\0"};
115  const char *const *safe_argv = special_case ? empty_argv : argv;
116  if (special_case) {
117  argc = 1;
118  }
119 
120  auto argv_size = static_cast<size_t>(argc);
121  // SetArgv* on python 3 takes wchar_t, so we have to convert.
122  std::unique_ptr<wchar_t *[]> widened_argv(new wchar_t *[argv_size]);
123  std::vector<std::unique_ptr<wchar_t[], detail::wide_char_arg_deleter>> widened_argv_entries;
124  widened_argv_entries.reserve(argv_size);
125  for (size_t ii = 0; ii < argv_size; ++ii) {
126  widened_argv_entries.emplace_back(detail::widen_chars(safe_argv[ii]));
127  if (!widened_argv_entries.back()) {
128  // A null here indicates a character-encoding failure or the python
129  // interpreter out of memory. Give up.
130  return;
131  }
132  widened_argv[ii] = widened_argv_entries.back().get();
133  }
134 
135  auto *pysys_argv = widened_argv.get();
136 
137  PySys_SetArgvEx(argc, pysys_argv, static_cast<int>(add_program_dir_to_path));
138 }
139 #endif
140 
142 
143 #if PY_VERSION_HEX >= PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX
144 inline void initialize_interpreter(PyConfig *config,
145  int argc = 0,
146  const char *const *argv = nullptr,
147  bool add_program_dir_to_path = true) {
149  PyStatus status = PyConfig_SetBytesArgv(config, argc, const_cast<char *const *>(argv));
150  if (PyStatus_Exception(status) != 0) {
151  // A failure here indicates a character-encoding failure or the python
152  // interpreter out of memory. Give up.
153  PyConfig_Clear(config);
154  throw std::runtime_error(PyStatus_IsError(status) != 0 ? status.err_msg
155  : "Failed to prepare CPython");
156  }
157  status = Py_InitializeFromConfig(config);
158  if (PyStatus_Exception(status) != 0) {
159  PyConfig_Clear(config);
160  throw std::runtime_error(PyStatus_IsError(status) != 0 ? status.err_msg
161  : "Failed to init CPython");
162  }
163  if (add_program_dir_to_path) {
164  PyRun_SimpleString("import sys, os.path; "
165  "sys.path.insert(0, "
166  "os.path.abspath(os.path.dirname(sys.argv[0])) "
167  "if sys.argv and os.path.exists(sys.argv[0]) else '')");
168  }
169  PyConfig_Clear(config);
170 }
171 #endif
172 
192 inline void initialize_interpreter(bool init_signal_handlers = true,
193  int argc = 0,
194  const char *const *argv = nullptr,
195  bool add_program_dir_to_path = true) {
196 #if PY_VERSION_HEX < PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX
198  init_signal_handlers, argc, argv, add_program_dir_to_path);
199 #else
200  PyConfig config;
201  PyConfig_InitPythonConfig(&config);
202  // See PR #4473 for background
203  config.parse_argv = 0;
204 
205  config.install_signal_handlers = init_signal_handlers ? 1 : 0;
206  initialize_interpreter(&config, argc, argv, add_program_dir_to_path);
207 #endif
208 }
209 
245 inline void finalize_interpreter() {
246  // Get the internals pointer (without creating it if it doesn't exist). It's possible for the
247  // internals to be created during Py_Finalize() (e.g. if a py::capsule calls `get_internals()`
248  // during destruction), so we get the pointer-pointer here and check it after Py_Finalize().
249  detail::internals **internals_ptr_ptr = detail::get_internals_pp();
250  // It could also be stashed in state_dict, so look there too:
251  if (object internals_obj
253  internals_ptr_ptr = detail::get_internals_pp_from_capsule(internals_obj);
254  }
255  // Local internals contains data managed by the current interpreter, so we must clear them to
256  // avoid undefined behaviors when initializing another interpreter
259 
260  Py_Finalize();
261 
262  if (internals_ptr_ptr) {
263  delete *internals_ptr_ptr;
264  *internals_ptr_ptr = nullptr;
265  }
266 }
267 
284 public:
285  explicit scoped_interpreter(bool init_signal_handlers = true,
286  int argc = 0,
287  const char *const *argv = nullptr,
288  bool add_program_dir_to_path = true) {
289  initialize_interpreter(init_signal_handlers, argc, argv, add_program_dir_to_path);
290  }
291 
292 #if PY_VERSION_HEX >= PYBIND11_PYCONFIG_SUPPORT_PY_VERSION_HEX
293  explicit scoped_interpreter(PyConfig *config,
294  int argc = 0,
295  const char *const *argv = nullptr,
296  bool add_program_dir_to_path = true) {
297  initialize_interpreter(config, argc, argv, add_program_dir_to_path);
298  }
299 #endif
300 
301  scoped_interpreter(const scoped_interpreter &) = delete;
302  scoped_interpreter(scoped_interpreter &&other) noexcept { other.is_valid = false; }
305 
307  if (is_valid) {
309  }
310  }
311 
312 private:
313  bool is_valid = true;
314 };
315 
name
Annotation for function names.
Definition: attr.h:51
embedded_module
Python 2.7/3.x compatible version of PyImport_AppendInittab and error checks.
Definition: embed.h:63
embedded_module::init_t
PyObject *(*)() init_t
Definition: embed.h:64
finalize_interpreter
void finalize_interpreter()
Definition: embed.h:245
embedded_module::embedded_module
embedded_module(const char *name, init_t init)
Definition: embed.h:65
wide_char_arg_deleter
Definition: embed.h:77
local_internals::registered_exception_translators
std::forward_list< ExceptionTranslator > registered_exception_translators
Definition: internals.h:546
PYBIND11_NAMESPACE_END
#define PYBIND11_NAMESPACE_END(name)
Definition: wrap/pybind11/include/pybind11/detail/common.h:80
detail
Definition: testSerializationNonlinear.cpp:70
initialize_interpreter_pre_pyconfig
void initialize_interpreter_pre_pyconfig(bool init_signal_handlers, int argc, const char *const *argv, bool add_program_dir_to_path)
Definition: embed.h:100
get_internals_pp_from_capsule
internals ** get_internals_pp_from_capsule(handle obj)
Definition: internals.h:458
PYBIND11_NAMESPACE_BEGIN
#define PYBIND11_NAMESPACE_BEGIN(name)
Definition: wrap/pybind11/include/pybind11/detail/common.h:76
result
Values result
Definition: OdometryOptimize.cpp:8
scoped_interpreter::is_valid
bool is_valid
Definition: embed.h:313
scoped_interpreter::scoped_interpreter
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:285
local_internals::registered_types_cpp
type_map< type_info * > registered_types_cpp
Definition: internals.h:545
initialize_interpreter
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:192
scoped_interpreter
Definition: embed.h:283
scoped_interpreter::~scoped_interpreter
~scoped_interpreter()
Definition: embed.h:306
eval.h
PYBIND11_NAMESPACE
Definition: test_custom_type_casters.cpp:24
widen_chars
wchar_t * widen_chars(const char *safe_arg)
Definition: embed.h:84
pybind11_fail
PyExc_RuntimeError PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Used internally.
Definition: wrap/pybind11/include/pybind11/detail/common.h:1013
pybind11.h
get_python_state_dict
object get_python_state_dict()
Definition: internals.h:434
get_internals_obj_from_state_dict
object get_internals_obj_from_state_dict(handle state_dict)
Definition: internals.h:454
get_local_internals
local_internals & get_local_internals()
Works like get_internals, but for things which are locally registered.
Definition: internals.h:584
get_internals_pp
internals **& get_internals_pp()
Definition: internals.h:322
precheck_interpreter
void precheck_interpreter()
Definition: embed.h:89
wide_char_arg_deleter::operator()
void operator()(wchar_t *ptr) const
Definition: embed.h:78
init
Definition: TutorialInplaceLU.cpp:2
scoped_interpreter::scoped_interpreter
scoped_interpreter(scoped_interpreter &&other) noexcept
Definition: embed.h:302
scoped_interpreter::operator=
scoped_interpreter & operator=(const scoped_interpreter &)=delete
pybind_wrapper_test_script.other
other
Definition: pybind_wrapper_test_script.py:42


gtsam
Author(s):
autogenerated on Thu Jun 13 2024 03:02:18