pythonogrosgeo

Segmentation fault returning OGR Layer object from function in Python


I have a simple programme that processes points from a Geopackage layer. On a first attempt I encapsulated file access into a function:

from osgeo import ogr

pointsFile = "points.gpkg"

def getPoints():

    driver = ogr.GetDriverByName("GPKG")
    dataSource = driver.Open(pointsFile, 0)
    layer = dataSource.GetLayer(0)
    print("Returning layer")
    return layer

def main():

    layer = getPoints()
    print("Number of points to process: ", layer.GetFeatureCount())


if __name__ == '__main__': main()

Which fails with a segmentation fault when it returns the layer object:

$ python3 testReturn.py
Returning layer
Segmentation fault (core dumped)

However, with file access inside main:

from osgeo import ogr

pointsFile = "points.gpkg"

def main():

    driver = ogr.GetDriverByName("GPKG")
    dataSource = driver.Open(pointsFile, 0)
    layer = dataSource.GetLayer(0)
    print("Number of points to process: ", layer.GetFeatureCount())


if __name__ == '__main__': main()

the programme runs as expected:

$ python3 testDirect.py
Number of points to process:  21872

What could be causing this issue?


Solution

  • Tested the code with GDB and the segmentation fault occurs when when calling:

    layer.GetFeatureCount()

    Some extra debugging information:

    Starting program: /usr/bin/python3 testReturn.py

    [Thread debugging using libthread_db enabled]

    Using host libthread_db library "/lib/x86_64-linux-gnu/libthread_db.so.1".

    Returning layer Program received signal SIGSEGV, Segmentation fault. 0x00007ffff5c42298 in OGR_L_GetFeatureCount () from /usr/local/lib/libgdal.so.20 (gdb)