μHAL (v2.8.17)
Part of the IPbus software repository
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
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#if PY_MAJOR_VERSION >= 3
23# define PYBIND11_EMBEDDED_MODULE_IMPL(name) \
24 extern "C" PyObject *pybind11_init_impl_##name(); \
25 extern "C" PyObject *pybind11_init_impl_##name() { return pybind11_init_wrapper_##name(); }
26#else
27# define PYBIND11_EMBEDDED_MODULE_IMPL(name) \
28 extern "C" void pybind11_init_impl_##name(); \
29 extern "C" void pybind11_init_impl_##name() { pybind11_init_wrapper_##name(); }
30#endif
31
47#define PYBIND11_EMBEDDED_MODULE(name, variable) \
48 static ::pybind11::module_::module_def PYBIND11_CONCAT(pybind11_module_def_, name); \
49 static void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ &); \
50 static PyObject PYBIND11_CONCAT(*pybind11_init_wrapper_, name)() { \
51 auto m = ::pybind11::module_::create_extension_module( \
52 PYBIND11_TOSTRING(name), nullptr, &PYBIND11_CONCAT(pybind11_module_def_, name)); \
53 try { \
54 PYBIND11_CONCAT(pybind11_init_, name)(m); \
55 return m.ptr(); \
56 } \
57 PYBIND11_CATCH_INIT_EXCEPTIONS \
58 } \
59 PYBIND11_EMBEDDED_MODULE_IMPL(name) \
60 ::pybind11::detail::embedded_module PYBIND11_CONCAT(pybind11_module_, name)( \
61 PYBIND11_TOSTRING(name), PYBIND11_CONCAT(pybind11_init_impl_, name)); \
62 void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ \
63 & variable) // NOLINT(bugprone-macro-parentheses)
64
67
68
70#if PY_MAJOR_VERSION >= 3
71 using init_t = PyObject *(*) ();
72#else
73 using init_t = void (*)();
74#endif
76 if (Py_IsInitialized() != 0) {
77 pybind11_fail("Can't add new modules after the interpreter has been initialized");
78 }
79
80 auto result = PyImport_AppendInittab(name, init);
81 if (result == -1) {
82 pybind11_fail("Insufficient memory to add a new module");
83 }
84 }
85};
86
88 void operator()(wchar_t *ptr) const {
89#if PY_VERSION_HEX >= 0x030500f0
90 // API docs: https://docs.python.org/3/c-api/sys.html#c.Py_DecodeLocale
91 PyMem_RawFree(ptr);
92#else
93 delete[] ptr;
94#endif
95 }
96};
97
98inline wchar_t *widen_chars(const char *safe_arg) {
99#if PY_VERSION_HEX >= 0x030500f0
100 wchar_t *widened_arg = Py_DecodeLocale(safe_arg, nullptr);
101#else
102 wchar_t *widened_arg = nullptr;
103
104// warning C4996: 'mbstowcs': This function or variable may be unsafe.
105# if defined(_MSC_VER)
106# pragma warning(push)
107# pragma warning(disable : 4996)
108# endif
109
110# if defined(HAVE_BROKEN_MBSTOWCS) && HAVE_BROKEN_MBSTOWCS
111 size_t count = std::strlen(safe_arg);
112# else
113 size_t count = std::mbstowcs(nullptr, safe_arg, 0);
114# endif
115 if (count != static_cast<size_t>(-1)) {
116 widened_arg = new wchar_t[count + 1];
117 std::mbstowcs(widened_arg, safe_arg, count + 1);
118 }
119
120# if defined(_MSC_VER)
121# pragma warning(pop)
122# endif
123
124#endif
125 return widened_arg;
126}
127
129inline void set_interpreter_argv(int argc, const char *const *argv, bool add_program_dir_to_path) {
130 // Before it was special-cased in python 3.8, passing an empty or null argv
131 // caused a segfault, so we have to reimplement the special case ourselves.
132 bool special_case = (argv == nullptr || argc <= 0);
133
134 const char *const empty_argv[]{"\0"};
135 const char *const *safe_argv = special_case ? empty_argv : argv;
136 if (special_case) {
137 argc = 1;
138 }
139
140 auto argv_size = static_cast<size_t>(argc);
141#if PY_MAJOR_VERSION >= 3
142 // SetArgv* on python 3 takes wchar_t, so we have to convert.
143 std::unique_ptr<wchar_t *[]> widened_argv(new wchar_t *[argv_size]);
144 std::vector<std::unique_ptr<wchar_t[], wide_char_arg_deleter>> widened_argv_entries;
145 widened_argv_entries.reserve(argv_size);
146 for (size_t ii = 0; ii < argv_size; ++ii) {
147 widened_argv_entries.emplace_back(widen_chars(safe_argv[ii]));
148 if (!widened_argv_entries.back()) {
149 // A null here indicates a character-encoding failure or the python
150 // interpreter out of memory. Give up.
151 return;
152 }
153 widened_argv[ii] = widened_argv_entries.back().get();
154 }
155
156 auto *pysys_argv = widened_argv.get();
157#else
158 // python 2.x
159 std::vector<std::string> strings{safe_argv, safe_argv + argv_size};
160 std::vector<char *> char_strings{argv_size};
161 for (std::size_t i = 0; i < argv_size; ++i)
162 char_strings[i] = &strings[i][0];
163 char **pysys_argv = char_strings.data();
164#endif
165
166 PySys_SetArgvEx(argc, pysys_argv, static_cast<int>(add_program_dir_to_path));
167}
168
170
171
190inline void initialize_interpreter(bool init_signal_handlers = true,
191 int argc = 0,
192 const char *const *argv = nullptr,
193 bool add_program_dir_to_path = true) {
194 if (Py_IsInitialized() != 0) {
195 pybind11_fail("The interpreter is already running");
196 }
197
198 Py_InitializeEx(init_signal_handlers ? 1 : 0);
199
200 detail::set_interpreter_argv(argc, argv, add_program_dir_to_path);
201}
202
238inline void finalize_interpreter() {
239 handle builtins(PyEval_GetBuiltins());
240 const char *id = PYBIND11_INTERNALS_ID;
241
242 // Get the internals pointer (without creating it if it doesn't exist). It's possible for the
243 // internals to be created during Py_Finalize() (e.g. if a py::capsule calls `get_internals()`
244 // during destruction), so we get the pointer-pointer here and check it after Py_Finalize().
245 detail::internals **internals_ptr_ptr = detail::get_internals_pp();
246 // It could also be stashed in builtins, so look there too:
247 if (builtins.contains(id) && isinstance<capsule>(builtins[id])) {
248 internals_ptr_ptr = capsule(builtins[id]);
249 }
250 // Local internals contains data managed by the current interpreter, so we must clear them to
251 // avoid undefined behaviors when initializing another interpreter
252 detail::get_local_internals().registered_types_cpp.clear();
253 detail::get_local_internals().registered_exception_translators.clear();
254
255 Py_Finalize();
256
257 if (internals_ptr_ptr) {
258 delete *internals_ptr_ptr;
259 *internals_ptr_ptr = nullptr;
260 }
261}
262
279public:
280 explicit scoped_interpreter(bool init_signal_handlers = true,
281 int argc = 0,
282 const char *const *argv = nullptr,
283 bool add_program_dir_to_path = true) {
284 initialize_interpreter(init_signal_handlers, argc, argv, add_program_dir_to_path);
285 }
286
288 scoped_interpreter(scoped_interpreter &&other) noexcept { other.is_valid = false; }
291
293 if (is_valid) {
295 }
296 }
297
298private:
299 bool is_valid = true;
300};
301
\rst Holds a reference to a Python object (no reference counting)
Definition: pytypes.h:194
\rst Scope guard version of initialize_interpreter and finalize_interpreter.
Definition: embed.h:278
scoped_interpreter & operator=(const scoped_interpreter &)=delete
scoped_interpreter(const scoped_interpreter &)=delete
scoped_interpreter & operator=(scoped_interpreter &&)=delete
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:280
scoped_interpreter(scoped_interpreter &&other) noexcept
Definition: embed.h:288
PYBIND11_NOINLINE void pybind11_fail(const char *reason)
Thrown when pybind11::cast or.
Definition: common.h:992
#define PYBIND11_NAMESPACE_END(name)
Definition: common.h:21
#define PYBIND11_NAMESPACE_BEGIN(name)
Definition: common.h:20
#define PYBIND11_INTERNALS_ID
Definition: internals.h:280
wchar_t * widen_chars(const char *safe_arg)
Definition: embed.h:98
void finalize_interpreter()
\rst Shut down the Python interpreter.
Definition: embed.h:238
void initialize_interpreter(bool init_signal_handlers=true, int argc=0, const char *const *argv=nullptr, bool add_program_dir_to_path=true)
\rst Initialize the Python interpreter.
Definition: embed.h:190
void set_interpreter_argv(int argc, const char *const *argv, bool add_program_dir_to_path)
Python 2.x/3.x-compatible version of PySys_SetArgv
Definition: embed.h:129
detail::initimpl::constructor< Args... > init()
Binds an existing constructor taking arguments Args...
Definition: pybind11.h:1900
void finalize_interpreter()
\rst Shut down the Python interpreter.
Definition: embed.h:244
void initialize_interpreter(PyConfig *config, int argc=0, const char *const *argv=nullptr, bool add_program_dir_to_path=true)
Definition: embed.h:144
Python 2.7/3.x compatible version of PyImport_AppendInittab and error checks.
Definition: embed.h:69
embedded_module(const char *name, init_t init)
Definition: embed.h:75
void(*)() init_t
Definition: embed.h:73
Annotation for function names.
Definition: attr.h:47
void operator()(wchar_t *ptr) const
Definition: embed.h:88