From df4486733e6108962e7732059c6b92a0006129ef Mon Sep 17 00:00:00 2001 From: wwmayer Date: Wed, 27 Aug 2025 00:46:30 +0200 Subject: [PATCH] Fem: Fix crash when writing mesh to z88 file For the z88 export the FemMesh must be passed to its Python wrapper which will increase the counter upon construction and decrease it upon destruction. If the counter becomes 0 the FemMesh will be destroyed too which causes a crash. To fix the crash the counter must be increased and safely decreased after the lifetime of the Python wrapper. This fixes https://github.com/FreeCAD/FreeCAD/issues/23380 --- src/Mod/Fem/App/FemMesh.cpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/Mod/Fem/App/FemMesh.cpp b/src/Mod/Fem/App/FemMesh.cpp index 597cec60a3..ffd8e2bbfb 100644 --- a/src/Mod/Fem/App/FemMesh.cpp +++ b/src/Mod/Fem/App/FemMesh.cpp @@ -2240,9 +2240,14 @@ void FemMesh::writeZ88(const std::string& FileName) const if (!module) { return; } + + // Make sure the reference counter won't become 0 when passing this mesh to its wrapper + FemMesh* self = const_cast(this); + self->ref(); + try { Py::Module z88mod(module, true); - Py::Object mesh = Py::asObject(new FemMeshPy(const_cast(this))); + Py::Object mesh = Py::asObject(new FemMeshPy(self)); Py::Callable method(z88mod.getAttr("write")); Py::Tuple args(2); args.setItem(0, mesh); @@ -2252,6 +2257,9 @@ void FemMesh::writeZ88(const std::string& FileName) const catch (Py::Exception& e) { e.clear(); } + + // Safely decrease the reference counter without destroying this mesh + self->unrefNoDelete(); }