Return layer from function in Python GDAL without Segmentation fault

trolleway
Nov 8, 2020

--

Using GDAL in Python is different from standart Python programing, due to memory pointers operation somewhere inside GDAL. Here is case with send layer from or into function.

Normal Python behavior causes segmentation failt at GetFeatureCount call

#!/usr/bin/python
# -*- coding: utf8 -*-
import os
import ogr, gdal
def open2mem(path):
ds = gdal.OpenEx(path,gdal.OF_READONLY)
assert ds is not None
layer = ds.GetLayer('multilinestrings')

driver_mem = ogr.GetDriverByName('MEMORY')
ds_mem = driver_mem.CreateDataSource('memData')
driver_mem.Open('memData',1)

layer_mem = ds_mem.CopyLayer(ds.GetLayer('multilinestrings'),'multilinestrings',['OVERWRITE=YES'])

return layer_mem
pbf1 = os.path.join('testdata','routes.osm.pbf')
routeslayer = open2mem(pbf1)

fc = routeslayer.GetFeatureCount()
print('features = '+str(fc))

You should keep datasource too. Just return it from function.

def open2mem(path):
return ds_mem, layer_mem
ds_mem, routeslayer = open2mem(pbf1)

Also, send layer with datasource to subfunctions

founded_route_feature = search_route(route_feature, routeslayer, ds_mem)

--

--

No responses yet