[QGIS-Developer] QgsGeometry's .get() and segfaults

Johannes Kröger (WhereGroup) johannes.kroeger at wheregroup.com
Thu Feb 22 06:56:46 PST 2024


Hi list!

I am using some time to learn more about the relationships between 
Python, C++, SIP, the QGIS API and everything in-between.

And currently I am confused why this Python snippet leads to a segfault:

from qgis.core import QgsGeometry
g = QgsGeometry.fromWkt("POINT (1 2)")
g_geom = g.get()
del g
print(g_geom.asWkt())

I understand that deleting wrapped objects can lead to unexpected 
deletions of related objects (e. g. if I delete a PyQt parent object and 
then try to use an existing reference/"variablename" to a child of it) 
but at least from the documentation this does not seem related to that.

https://github.com/qgis/QGIS/blob/dc73608a60229c9960ee65e308cfaba5f32566ec/src/core/geometry/qgsgeometry.h#L196 
says about QgsGeometry.get():
 > Returns a modifiable (non-const) reference to the underlying abstract 
geometry primitive. This method can be slow to call, as it may trigger a 
detachment of the geometry and a deep copy. Where possible, use 
constGet() instead.

I do not understand anything in the detach() function itself 
https://github.com/qgis/QGIS/blob/dc73608a60229c9960ee65e308cfaba5f32566ec/src/core/geometry/qgsgeometry.cpp#L102 
:o)

Would my small snippet lead to a reference to the C++ object's geometry? 
Then I'd understand the segfault (although not why it would not trigger 
one of the usual "wrapped C/C++ object of type [...] has been deleted" 
errors) if I try to access it after the whole QgsGeometry might have 
been destroyed.
Or does it get a "detached deep copy"? In that case it sounds like an 
independent object to me but I might be completely wrong.

Are there any C++ or SIP terms you could throw my way for further reading?

Thanks for your help!

Cheers, Hannes



More information about the QGIS-Developer mailing list