Skip to content

Commit 9aa676d

Browse files
fix: clear local internals after finalizing interpreter #2101 (#3744)
* Clear local internals after finalizing interpreter * Add descriptive comments * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 44596bc commit 9aa676d

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

include/pybind11/embed.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,10 @@ inline void finalize_interpreter() {
198198
if (builtins.contains(id) && isinstance<capsule>(builtins[id])) {
199199
internals_ptr_ptr = capsule(builtins[id]);
200200
}
201+
// Local internals contains data managed by the current interpreter, so we must clear them to
202+
// avoid undefined behaviors when initializing another interpreter
203+
detail::get_local_internals().registered_types_cpp.clear();
204+
detail::get_local_internals().registered_exception_translators.clear();
201205

202206
Py_Finalize();
203207

tests/test_embed/test_interpreter.cpp

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -375,3 +375,21 @@ TEST_CASE("sys.argv gets initialized properly") {
375375
}
376376
py::initialize_interpreter();
377377
}
378+
379+
TEST_CASE("make_iterator can be called before then after finalizing an interpreter") {
380+
// Reproduction of issue #2101 (https://github.com/pybind/pybind11/issues/2101)
381+
py::finalize_interpreter();
382+
383+
std::vector<int> container;
384+
{
385+
pybind11::scoped_interpreter g;
386+
auto iter = pybind11::make_iterator(container.begin(), container.end());
387+
}
388+
389+
REQUIRE_NOTHROW([&]() {
390+
pybind11::scoped_interpreter g;
391+
auto iter = pybind11::make_iterator(container.begin(), container.end());
392+
}());
393+
394+
py::initialize_interpreter();
395+
}

0 commit comments

Comments
 (0)