Skip to content

Commit d706c7a

Browse files
committed
More robust module teardown.
1 parent 55182c4 commit d706c7a

File tree

1 file changed

+15
-12
lines changed

1 file changed

+15
-12
lines changed

src/_mplcairo.cpp

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1518,19 +1518,22 @@ PYBIND11_MODULE(_mplcairo, m)
15181518
py::module::import("matplotlib.mathtext")
15191519
.attr("MathTextParser")("mplcairo");
15201520

1521-
auto cleanup = py::cpp_function{
1522-
[&](py::handle weakref) -> void {
1523-
FT_Done_FreeType(detail::ft_library);
1524-
1525-
// Make sure that these objects don't outlive the Python interpreter.
1526-
detail::UNIT_CIRCLE = {};
1527-
detail::PIXEL_MARKER = {};
1528-
GraphicsContextRenderer::mathtext_parser_ = {};
1529-
1530-
weakref.dec_ref();
1521+
py::module::import("atexit").attr("register")(
1522+
py::cpp_function{
1523+
[&]() -> void {
1524+
FT_Done_FreeType(detail::ft_library);
1525+
// Make sure that these objects don't outlive the Python interpreter.
1526+
// (It appears that sometimes, a weakref callback to the module doesn't
1527+
// get called at shutdown, so if we rely on that approach instead of
1528+
// using `atexit.register`, we may get a segfault when Python tries to
1529+
// deallocate the type objects (via a decref by the C++ destructor) too
1530+
// late in the shutdown sequence.)
1531+
detail::UNIT_CIRCLE = {};
1532+
detail::PIXEL_MARKER = {};
1533+
GraphicsContextRenderer::mathtext_parser_ = {};
1534+
}
15311535
}
1532-
};
1533-
py::weakref(m, cleanup).release();
1536+
);
15341537

15351538
// Export symbols.
15361539

0 commit comments

Comments
 (0)