\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 calle
| 241 | |
| 242 | \endrst */ |
| 243 | inline void finalize_interpreter() { |
| 244 | // get rid of any thread-local interpreter cache that currently exists |
| 245 | if (detail::has_seen_non_main_interpreter()) { |
| 246 | detail::get_internals_pp_manager().unref(); |
| 247 | detail::get_local_internals_pp_manager().unref(); |
| 248 | |
| 249 | // We know there can be no other interpreter alive now |
| 250 | detail::has_seen_non_main_interpreter() = false; |
| 251 | } |
| 252 | |
| 253 | // Re-fetch the internals pointer-to-pointer (but not the internals itself, which might not |
| 254 | // exist). It's possible for the internals to be created during Py_Finalize() (e.g. if a |
| 255 | // py::capsule calls `get_internals()` during destruction), so we get the pointer-pointer here |
| 256 | // and check it after Py_Finalize(). |
| 257 | detail::get_internals_pp_manager().get_pp(); |
| 258 | detail::get_local_internals_pp_manager().get_pp(); |
| 259 | |
| 260 | Py_Finalize(); |
| 261 | |
| 262 | detail::get_internals_pp_manager().destroy(); |
| 263 | |
| 264 | // Local internals contains data managed by the current interpreter, so we must clear them to |
| 265 | // avoid undefined behaviors when initializing another interpreter |
| 266 | detail::get_local_internals_pp_manager().destroy(); |
| 267 | |
| 268 | // We know there is no interpreter alive now, so we can reset the multi-flag |
| 269 | detail::has_seen_non_main_interpreter() = false; |
| 270 | } |
| 271 | |
| 272 | /** \rst |
| 273 | Scope guard version of `initialize_interpreter` and `finalize_interpreter`. |
no test coverage detected