Skip to content

Commit 42455b5

Browse files
StarQTiuspre-commit-ci[bot]
authored andcommitted
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 93d68dd commit 42455b5

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
@@ -247,6 +247,10 @@ inline void finalize_interpreter() {
247247
if (builtins.contains(id) && isinstance<capsule>(builtins[id])) {
248248
internals_ptr_ptr = capsule(builtins[id]);
249249
}
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();
250254

251255
Py_Finalize();
252256

tests/test_embed/test_interpreter.cpp

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

0 commit comments

Comments
 (0)