15 #if defined(PYPY_VERSION)
16 # error Embedding the interpreter is not supported with PyPy
19 #if PY_MAJOR_VERSION >= 3
20 # define PYBIND11_EMBEDDED_MODULE_IMPL(name) \
21 extern "C" PyObject *pybind11_init_impl_##name(); \
22 extern "C" PyObject *pybind11_init_impl_##name() { \
23 return pybind11_init_wrapper_##name(); \
26 # define PYBIND11_EMBEDDED_MODULE_IMPL(name) \
27 extern "C" void pybind11_init_impl_##name(); \
28 extern "C" void pybind11_init_impl_##name() { \
29 pybind11_init_wrapper_##name(); \
48 #define PYBIND11_EMBEDDED_MODULE(name, variable) \
49 static ::pybind11::module_::module_def \
50 PYBIND11_CONCAT(pybind11_module_def_, name); \
51 static void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ &); \
52 static PyObject PYBIND11_CONCAT(*pybind11_init_wrapper_, name)() { \
53 auto m = ::pybind11::module_::create_extension_module( \
54 PYBIND11_TOSTRING(name), nullptr, \
55 &PYBIND11_CONCAT(pybind11_module_def_, name)); \
57 PYBIND11_CONCAT(pybind11_init_, name)(m); \
59 } PYBIND11_CATCH_INIT_EXCEPTIONS \
61 PYBIND11_EMBEDDED_MODULE_IMPL(name) \
62 ::pybind11::detail::embedded_module PYBIND11_CONCAT(pybind11_module_, name) \
63 (PYBIND11_TOSTRING(name), \
64 PYBIND11_CONCAT(pybind11_init_impl_, name)); \
65 void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ &variable)
68 PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
69 PYBIND11_NAMESPACE_BEGIN(detail)
73 #if PY_MAJOR_VERSION >= 3
74 using init_t = PyObject *(*)();
76 using init_t = void (*)();
78 embedded_module(
const char *
name, init_t init) {
79 if (Py_IsInitialized())
80 pybind11_fail(
"Can't add new modules after the interpreter has been initialized");
82 auto result = PyImport_AppendInittab(name, init);
84 pybind11_fail(
"Insufficient memory to add a new module");
88 PYBIND11_NAMESPACE_END(detail)
103 inline
void initialize_interpreter(
bool init_signal_handlers = true) {
104 if (Py_IsInitialized())
105 pybind11_fail(
"The interpreter is already running");
107 Py_InitializeEx(init_signal_handlers ? 1 : 0);
148 inline void finalize_interpreter() {
149 handle builtins(PyEval_GetBuiltins());
150 const char *
id = PYBIND11_INTERNALS_ID;
155 detail::internals **internals_ptr_ptr = detail::get_internals_pp();
157 if (builtins.contains(
id) && isinstance<capsule>(builtins[id]))
158 internals_ptr_ptr =
capsule(builtins[
id]);
162 if (internals_ptr_ptr) {
163 delete *internals_ptr_ptr;
164 *internals_ptr_ptr =
nullptr;
184 initialize_interpreter(init_signal_handlers);
194 finalize_interpreter();
198 bool is_valid =
true;
201 PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
static module_ import(const char *name)
Import and return a module or throws error_already_set.
Python 2.7/3.x compatible version of PyImport_AppendInittab and error checks.
Annotation for function names.