I'm trying to create a shapefile layer based on the spatial projection of an already existing raster. (Ultimately, this will be used in gdal.Polygonize to get a shape from my raster data.) However, I am encountering an error when trying to use CreateLayer.

  • raster_uri- location of the raster file that I want to make into a shapefile. I know this exists.
  • out_uri- Location I want the new shapefile to print to.
  • layer_name- String layer name input.
  • filed_name- String field name input.

This is the code that I was using.

raster = gdal.Open(raster_uri)
driver = ogr.GetDriverByName("ESRI Shapefile")
ds = driver.CreateDataSource(out_uri)

spat_ref = osr.SpatialReference()
proj = raster.GetProjectionRef()

layer = ds.CreateLayer(layer_name, spat_ref, ogr.wkbPolygon)

It yields this error message:

TypeError: in method 'DataSource_CreateLayer', argument 2 of type 'char const *'

Outputing the type of spat_ref shows up as <class 'osgeo.osr.SpatialReference'> so I'm unsure what char const * it's complaining about.

Interestingly, if I try to do this all from a python shell using the same file, layer creates just fine. Any ideas on what might be the issue?

2 Answers 2


As it turns out, creating a layer name on an ESRI shapefile can't be done using a unicode string. Since way back in my file system, I was dynamically pulling layer names from a set of file names, I was allowing for unicode, but it is unsupported with that CreateLayer(). The issue was (sort of fixed) by doing the following:

layer_name = layer_name.encode('utf-8')
layer = ds.CreateLayer(layer_name, spat_ref, ogr.wkbPolygon)

Now it runs just fine, though with a slightly smaller potential character set.

  • Thanks for the answer, helped me eventually solve my issue. I dug deeper and found a related post on SO that explains it well; I will condense my findings in an answer so it can help others as well. (spoiler: just casting to string solved my issue)
    – DarkCygnus
    Commented Jan 25, 2019 at 16:31

Digging deeper on this issue I found this SO answer that provided a solution to the problem I was having.

It seems that, in your case here, your layer_name contains some Unicode characters, which can't be converted in a trivial manner to a 'char const *', and the reason why you get the exception.

This is why the solution proposed in the accepted answer works, as it changes it's encoding to a UTF-8 byte string, which can be easily converted to 'char const*' (coincidentally, that was also suggested in another answer on the same SO post).

What worked for me as an alternative is to simply cast your layer_name to string by doing:

layer = ds.CreateLayer(str(layer_name), spat_ref, ogr.wkbPolygon)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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