2

Just recently I was trying to get the geometry of a polygon stored in an ESRI Shapefile. In the script I was trying to read the polygon as follows:

import ogr
path = "shape.shp"
ds = ogr.Open(path, 0)
layer = ds.GetLayer()
layer.GetFeature(0).GetGeometryRef().GetGeometryName()

which resulted in a memory access error.

I then tried this:

import ogr
path = "shape.shp"
ds = ogr.Open(path, 0)
layer = ds.GetLayer()
layer.GetFeature(0).Clone().GetGeometryRef().GetGeometryName()

Which worked.

Why does that work but not the other approach? Which of them is 'right'?

3

The osgeo module is not really very "Pythonic" (SWIG generated Python bindings for the GDAL and OGR C/C++ libraries)

Your first solution does not work. Why ?
Look at segfault with Clone() called on GeometryRef of Feature

This is definitely a variable scoping issue. I would call it a bug, but it isn't going to be fixed any time soon. Please use more verbose method calls to ensure intermediate variables do not go out of scope.

The log of the crash confirming the precedent remark is

Exception Type:        EXC_BAD_ACCESS (SIGSEGV)
Exception Codes:       KERN_INVALID_ADDRESS at 0x0000000000000090

Therefore this more verbose solution work:

from osgeo import ogr
ds = ogr.Open("test.shp")
layer = ds.GetLayer(0)
# first feature
feat = layer.GetFeature(0)
geom = feat.GetGeometryRef()
print geom.GetGeometryName()
LINESTRING

When you use layer.GetFeature(0).Clone() you work with a copy of the feature (different) (OGRFeature * OGRFeature::Clone()) with fewer problems.

That is why Sean Gillies creates Fiona to "simplify" the Python port of the C/C++ ogr library.

import fiona
layer = fiona.open("test.shp")
print layer.schema['geometry']
LineString
# directly
print fiona.open("test.shp").schema['geometry']
LineString
  • Thank you very much! Sadly I cannot use fiona, but in this case python is just fine. – JustBasti Dec 1 '15 at 9:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.