[gdal-dev] OGRGeometry creation
Mateusz Loskot
mateusz at loskot.net
Fri Nov 23 07:57:42 EST 2007
Yuriy Rusinov wrote:
> Dear Colleagues !
>
> I try to create geometry object using wkt-string. I do
>
> OGRGeometry * poOGRGeom;
> const char* obWkt = "POLYGON((...,...))";
> char * pszWkt = new char [strlen (obWkt)];
You need strlen(obWkt) + 1, to have room for \0 character
> strncpy (pszWkt, obWkt, strlen (obWkt));
> OGRSpatialReference *ref = new OGRSpatialReference ();
Not necessary, you can pass NULL instead of empty SRS.
> OGRErr ier = OGRGeometryFactory::createFromWkt (&pszWkt, ref,
> &poOGRGeom);
> if (ier == OGRERR_NONE)
> {
> char ** wkt = new char*;
> wkt[0] = new char[1000];
Here is the bug.
You don't need to allocate memory for output wkt.
The manual says:
"ppszDstText - a text buffer is allocated by the program, and assigned
to the passed pointer."
http://www.gdal.org/ogr/classOGRGeometry.html#71184265101d21cffa5c50ee79afdd61
> poOGRGeom->exportToWkt (wkt);
> ...
> }
>
> This code works fine under Linux, but under Windows (Visual Studio 2003) it
> fails on call of any function-member OGRGeometry class. Where is the
> troubles ?
This is random problem caused by incorrect (re)allocation of output
buffer pointed above. Here is complete code of your example that
presents how correctly import/export WKT to/from OGRGeometry:
////////////////////////////////////////////////////////////////////
#include <ogrsf_frmts.h>
#include <iostream>
#include <cstdlib>
#include <cassert>
int main()
{
OGRRegisterAll();
OGRGeometry * poOGRGeom = NULL;
const char* obWkt = "POLYGON((0 0,4 0,4 4,0 4,0 0),(1 1,2 1,2 2,1
2,1 1))";
// Copy WKT to new 'iteratable' buffer
std::size_t size = strlen(obWkt);
char * pszWkt = new char [size + 1];
memset(pszWkt, 0, size);
strncpy(pszWkt, obWkt, size);
// You don't need this, you can pass NULL
// if you do not need specific SRS
OGRSpatialReference *ref = new OGRSpatialReference ();
// Use copy of ptr, as we need the original for deallocation
// createFromWkt uses passed WKT ptr as iterator, so it will point
// to pass-the-end after all
char* p = pszWkt;
OGRErr ier = OGRGeometryFactory::createFromWkt (&p, ref, &poOGRGeom);
delete [] pszWkt;
if (ier == OGRERR_NONE)
{
// exportToWkt will allocate memory for WKT
char* wkt = NULL;
poOGRGeom->exportToWkt(&wkt);
assert(NULL != wkt);
std::cout << wkt << std::endl;
// Important cleanup
CPLFree(wkt);
}
OGRGeometryFactory::destroyGeometry(poOGRGeom);
return 0;
}
////////////////////////////////////////////////////////////////////
Cheers
--
Mateusz Loskot
http://mateusz.loskot.net
More information about the gdal-dev
mailing list