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
This commit is contained in:
wwmayer
2025-08-27 00:46:30 +02:00
committed by Kacper Donat
parent 5af7ad5df4
commit 8944fd7d5e

View File

@@ -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<FemMesh*>(this);
self->ref();
try {
Py::Module z88mod(module, true);
Py::Object mesh = Py::asObject(new FemMeshPy(const_cast<FemMesh*>(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();
}