2017-03-29 22:20:42 +00:00
|
|
|
/*
|
|
|
|
pybind11/embed.h: Support for embedding the interpreter
|
|
|
|
|
|
|
|
Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>
|
|
|
|
|
|
|
|
All rights reserved. Use of this source code is governed by a
|
|
|
|
BSD-style license that can be found in the LICENSE file.
|
|
|
|
*/
|
|
|
|
|
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include "pybind11.h"
|
|
|
|
#include "eval.h"
|
|
|
|
|
|
|
|
#if defined(PYPY_VERSION)
|
|
|
|
# error Embedding the interpreter is not supported with PyPy
|
|
|
|
#endif
|
|
|
|
|
|
|
|
#if PY_MAJOR_VERSION >= 3
|
|
|
|
# define PYBIND11_EMBEDDED_MODULE_IMPL(name) \
|
2019-10-17 08:43:33 +00:00
|
|
|
extern "C" PyObject *pybind11_init_impl_##name(); \
|
2017-03-29 22:20:42 +00:00
|
|
|
extern "C" PyObject *pybind11_init_impl_##name() { \
|
|
|
|
return pybind11_init_wrapper_##name(); \
|
|
|
|
}
|
|
|
|
#else
|
|
|
|
# define PYBIND11_EMBEDDED_MODULE_IMPL(name) \
|
2019-10-17 08:43:33 +00:00
|
|
|
extern "C" void pybind11_init_impl_##name(); \
|
2017-03-29 22:20:42 +00:00
|
|
|
extern "C" void pybind11_init_impl_##name() { \
|
|
|
|
pybind11_init_wrapper_##name(); \
|
|
|
|
}
|
|
|
|
#endif
|
|
|
|
|
|
|
|
/** \rst
|
|
|
|
Add a new module to the table of builtins for the interpreter. Must be
|
|
|
|
defined in global scope. The first macro parameter is the name of the
|
|
|
|
module (without quotes). The second parameter is the variable which will
|
|
|
|
be used as the interface to add functions and classes to the module.
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
PYBIND11_EMBEDDED_MODULE(example, m) {
|
|
|
|
// ... initialize functions and classes here
|
|
|
|
m.def("foo", []() {
|
|
|
|
return "Hello, World!";
|
|
|
|
});
|
|
|
|
}
|
|
|
|
\endrst */
|
|
|
|
#define PYBIND11_EMBEDDED_MODULE(name, variable) \
|
2017-09-13 17:02:53 +00:00
|
|
|
static void PYBIND11_CONCAT(pybind11_init_, name)(pybind11::module &); \
|
|
|
|
static PyObject PYBIND11_CONCAT(*pybind11_init_wrapper_, name)() { \
|
|
|
|
auto m = pybind11::module(PYBIND11_TOSTRING(name)); \
|
2017-03-29 22:20:42 +00:00
|
|
|
try { \
|
2017-09-13 17:02:53 +00:00
|
|
|
PYBIND11_CONCAT(pybind11_init_, name)(m); \
|
2017-03-29 22:20:42 +00:00
|
|
|
return m.ptr(); \
|
|
|
|
} catch (pybind11::error_already_set &e) { \
|
|
|
|
PyErr_SetString(PyExc_ImportError, e.what()); \
|
|
|
|
return nullptr; \
|
|
|
|
} catch (const std::exception &e) { \
|
|
|
|
PyErr_SetString(PyExc_ImportError, e.what()); \
|
|
|
|
return nullptr; \
|
|
|
|
} \
|
|
|
|
} \
|
|
|
|
PYBIND11_EMBEDDED_MODULE_IMPL(name) \
|
2017-09-13 17:02:53 +00:00
|
|
|
pybind11::detail::embedded_module name(PYBIND11_TOSTRING(name), \
|
|
|
|
PYBIND11_CONCAT(pybind11_init_impl_, name)); \
|
|
|
|
void PYBIND11_CONCAT(pybind11_init_, name)(pybind11::module &variable)
|
2017-03-29 22:20:42 +00:00
|
|
|
|
|
|
|
|
2017-08-10 16:03:29 +00:00
|
|
|
NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
|
2017-03-29 22:20:42 +00:00
|
|
|
NAMESPACE_BEGIN(detail)
|
|
|
|
|
|
|
|
/// Python 2.7/3.x compatible version of `PyImport_AppendInittab` and error checks.
|
|
|
|
struct embedded_module {
|
|
|
|
#if PY_MAJOR_VERSION >= 3
|
|
|
|
using init_t = PyObject *(*)();
|
|
|
|
#else
|
|
|
|
using init_t = void (*)();
|
|
|
|
#endif
|
|
|
|
embedded_module(const char *name, init_t init) {
|
|
|
|
if (Py_IsInitialized())
|
|
|
|
pybind11_fail("Can't add new modules after the interpreter has been initialized");
|
|
|
|
|
|
|
|
auto result = PyImport_AppendInittab(name, init);
|
|
|
|
if (result == -1)
|
|
|
|
pybind11_fail("Insufficient memory to add a new module");
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
NAMESPACE_END(detail)
|
|
|
|
|
|
|
|
/** \rst
|
|
|
|
Initialize the Python interpreter. No other pybind11 or CPython API functions can be
|
|
|
|
called before this is done; with the exception of `PYBIND11_EMBEDDED_MODULE`. The
|
|
|
|
optional parameter can be used to skip the registration of signal handlers (see the
|
2018-11-01 01:10:11 +00:00
|
|
|
`Python documentation`_ for details). Calling this function again after the interpreter
|
2017-03-29 22:20:42 +00:00
|
|
|
has already been initialized is a fatal error.
|
2018-11-01 01:10:11 +00:00
|
|
|
|
|
|
|
If initializing the Python interpreter fails, then the program is terminated. (This
|
|
|
|
is controlled by the CPython runtime and is an exception to pybind11's normal behavior
|
|
|
|
of throwing exceptions on errors.)
|
|
|
|
|
|
|
|
.. _Python documentation: https://docs.python.org/3/c-api/init.html#c.Py_InitializeEx
|
2017-03-29 22:20:42 +00:00
|
|
|
\endrst */
|
|
|
|
inline void initialize_interpreter(bool init_signal_handlers = true) {
|
|
|
|
if (Py_IsInitialized())
|
|
|
|
pybind11_fail("The interpreter is already running");
|
|
|
|
|
|
|
|
Py_InitializeEx(init_signal_handlers ? 1 : 0);
|
|
|
|
|
|
|
|
// Make .py files in the working directory available by default
|
Make PYBIND11_OBJECT_CVT only convert if the type check fails
Currently types that are capable of conversion always call their convert
function when invoked with a `py::object` which is actually the correct
type. This means that code such as `py::cast<py::list>(obj)` and
`py::list l(obj.attr("list"))` make copies, which was an oversight
rather than an intentional feature.
While at first glance there might be something behind having
`py::list(obj)` make a copy (as it would in Python), this would be
inconsistent when you dig a little deeper because `py::list(l)`
*doesn't* make a copy for an existing `py::list l`, and having an
inconsistency within C++ would be worse than a C++ <-> Python
inconsistency.
It is possible to get around the copying using a
`reinterpret_borrow<list>(o)` (and this commit fixes one place, in
`embed.h`, that does so), but that seems a misuse of
`reinterpret_borrow`, which is really supposed to be just for dealing
with raw python-returned values, not `py::object`-derived wrappers which
are supposed to be higher level.
This changes the constructor of such converting types (i.e. anything
using PYBIND11_OBJECT_CVT -- `str`, `bool_`, `int_`, `float_`, `tuple`,
`dict`, `list`, `set`, `memoryview`) to reference rather than copy when
the check function passes.
It also adds an `object &&` constructor that is slightly more efficient
by avoiding an inc_ref when the check function passes.
2017-08-03 23:27:04 +00:00
|
|
|
module::import("sys").attr("path").cast<list>().append(".");
|
2017-03-29 22:20:42 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/** \rst
|
|
|
|
Shut down the Python interpreter. No pybind11 or CPython API functions can be called
|
|
|
|
after this. In addition, pybind11 objects must not outlive the interpreter:
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
{ // BAD
|
|
|
|
py::initialize_interpreter();
|
|
|
|
auto hello = py::str("Hello, World!");
|
|
|
|
py::finalize_interpreter();
|
|
|
|
} // <-- BOOM, hello's destructor is called after interpreter shutdown
|
|
|
|
|
|
|
|
{ // GOOD
|
|
|
|
py::initialize_interpreter();
|
|
|
|
{ // scoped
|
|
|
|
auto hello = py::str("Hello, World!");
|
|
|
|
} // <-- OK, hello is cleaned up properly
|
|
|
|
py::finalize_interpreter();
|
|
|
|
}
|
|
|
|
|
|
|
|
{ // BETTER
|
|
|
|
py::scoped_interpreter guard{};
|
|
|
|
auto hello = py::str("Hello, World!");
|
|
|
|
}
|
|
|
|
|
|
|
|
.. warning::
|
|
|
|
|
2017-04-20 21:40:56 +00:00
|
|
|
The interpreter can be restarted by calling `initialize_interpreter` again.
|
|
|
|
Modules created using pybind11 can be safely re-initialized. However, Python
|
|
|
|
itself cannot completely unload binary extension modules and there are several
|
|
|
|
caveats with regard to interpreter restarting. All the details can be found
|
|
|
|
in the CPython documentation. In short, not all interpreter memory may be
|
|
|
|
freed, either due to reference cycles or user-created global data.
|
2017-03-29 22:20:42 +00:00
|
|
|
|
|
|
|
\endrst */
|
2017-04-20 21:40:56 +00:00
|
|
|
inline void finalize_interpreter() {
|
|
|
|
handle builtins(PyEval_GetBuiltins());
|
|
|
|
const char *id = PYBIND11_INTERNALS_ID;
|
|
|
|
|
2017-06-07 15:35:39 +00:00
|
|
|
// Get the internals pointer (without creating it if it doesn't exist). It's possible for the
|
|
|
|
// internals to be created during Py_Finalize() (e.g. if a py::capsule calls `get_internals()`
|
|
|
|
// during destruction), so we get the pointer-pointer here and check it after Py_Finalize().
|
2018-01-11 23:46:10 +00:00
|
|
|
detail::internals **internals_ptr_ptr = detail::get_internals_pp();
|
2017-06-07 15:35:39 +00:00
|
|
|
// It could also be stashed in builtins, so look there too:
|
2017-04-20 21:40:56 +00:00
|
|
|
if (builtins.contains(id) && isinstance<capsule>(builtins[id]))
|
|
|
|
internals_ptr_ptr = capsule(builtins[id]);
|
|
|
|
|
|
|
|
Py_Finalize();
|
|
|
|
|
|
|
|
if (internals_ptr_ptr) {
|
|
|
|
delete *internals_ptr_ptr;
|
|
|
|
*internals_ptr_ptr = nullptr;
|
|
|
|
}
|
|
|
|
}
|
2017-03-29 22:20:42 +00:00
|
|
|
|
|
|
|
/** \rst
|
|
|
|
Scope guard version of `initialize_interpreter` and `finalize_interpreter`.
|
|
|
|
This a move-only guard and only a single instance can exist.
|
|
|
|
|
|
|
|
.. code-block:: cpp
|
|
|
|
|
|
|
|
#include <pybind11/embed.h>
|
|
|
|
|
|
|
|
int main() {
|
|
|
|
py::scoped_interpreter guard{};
|
|
|
|
py::print(Hello, World!);
|
|
|
|
} // <-- interpreter shutdown
|
|
|
|
\endrst */
|
|
|
|
class scoped_interpreter {
|
|
|
|
public:
|
|
|
|
scoped_interpreter(bool init_signal_handlers = true) {
|
|
|
|
initialize_interpreter(init_signal_handlers);
|
|
|
|
}
|
|
|
|
|
|
|
|
scoped_interpreter(const scoped_interpreter &) = delete;
|
|
|
|
scoped_interpreter(scoped_interpreter &&other) noexcept { other.is_valid = false; }
|
|
|
|
scoped_interpreter &operator=(const scoped_interpreter &) = delete;
|
|
|
|
scoped_interpreter &operator=(scoped_interpreter &&) = delete;
|
|
|
|
|
|
|
|
~scoped_interpreter() {
|
|
|
|
if (is_valid)
|
|
|
|
finalize_interpreter();
|
|
|
|
}
|
|
|
|
|
|
|
|
private:
|
|
|
|
bool is_valid = true;
|
|
|
|
};
|
|
|
|
|
2017-08-10 16:03:29 +00:00
|
|
|
NAMESPACE_END(PYBIND11_NAMESPACE)
|