我编写了这段代码是为了在 opengl 窗口中显示线形文件。
实际上,它是代码项目中的 OpenGL 中渲染 Shapefile 的代码,但我对其进行了一些更改,以便使用 OGR 库而不是 shapelib 读取形状。
#include "ogrsf_frmts.h"
//#include "shapelib\shapefil.h"
void OpenShapeFile(char* filename)
{
int i = 0;
int j = 0;
OGRErr error;
OGRDataSource *poDataSource;
poDataSource = OGRSFDriverRegistrar::Open(filename,false);
OGRLayer *poLayer;
poLayer = poDataSource ->GetLayer(0);
OGREnvelope *poEnvelope = new OGREnvelope();
error = poLayer ->GetExtent(poEnvelope,true);
sBoundingBox.fMaxX = poEnvelope ->MaxX;
sBoundingBox.fMaxY = poEnvelope ->MaxY;
sBoundingBox.fMinX = poEnvelope ->MinX;
sBoundingBox.fMinY = poEnvelope ->MinY;
delete poEnvelope;
OGRwkbGeometryType GeometryType = poLayer ->GetGeomType();
int NumberOfFeatures = poLayer ->GetFeatureCount(true);
poLayer ->ResetReading();
//Line Shapefile
if ( wkbFlatten ( GeometryType ) == wkbLineString )
{
OGRFeature *poFeature;
MyLineString2D lineString;
//temporary pointer in order to store coordinates of individual line vertexes
OGRPoint *poPointTemp = new OGRPoint();
for ( i = 0; i < NumberOfFeatures; i++ )
{
poFeature = poLayer ->GetNextFeature();
OGRGeometry *poGeometry;
poGeometry = poFeature ->GetGeometryRef();
if ( poGeometry != NULL )
{
OGRLineString *poLineString = (OGRLineString *)poGeometry;
int NumberOfVertexes = poLineString ->getNumPoints();
lineString.vPointList.resize(NumberOfVertexes);
for ( j = 0; j < NumberOfVertexes ; j++ )
{
poLineString ->getPoint(j,poPointTemp);
MyPoint2D ptTemp;
ptTemp.dX = poPointTemp ->getX();
ptTemp.dY = poPointTemp ->getY();
lineString.vPointList.at(j) = ptTemp;
}
vLines.push_back(lineString);
}
OGRFeature::DestroyFeature( poFeature );
}
delete poPointTemp;
}
}
void initializeGL()
{
//glClearColor (0.0, 0.0, 0.0, 0.0);
glClearColor (1.0, 1.0, 1.0, 1.0);
int main(int argc, char** argv)
{
//OpenShapeFile("Shapefiles\\poi.shp");//Point Shapefile
OpenShapeFile("Shapefiles\\strassen.shp");//Line Shapefile
//OpenShapeFile("Shapefiles\\gruenflaechen.shp");//Polygon Shapefile
当我评论该行时:
delete poPointTemp;
没有错误,并且正确地在 OpenGL 窗口上绘制了形状。但正如你所知,这是一种内存泄漏,所以当我不需要时,poPointTemp
我应该删除它。
但在这条线上:
delete poPointTemp;
我收到运行时错误:
我已经调试了我的代码,运行此行之前的地址和内容poPointTemp
如下:
poPointTemp 0x00503a90 {x=3435936.3300000001 y=5790327.5999999996 z=0.00000000000000000 }
我的意思poPointTemp
是不是 NULL 指针,而且我们无权访问的地址与poPointTemp
's 地址不同!!!
你认为我的代码有什么问题?
我试图尽可能地减少代码。因此,如果您想自己调试代码,您可以在代码项目中下载它,然后根据我上面编写的代码对其进行更改。
当然,在约翰的回答的帮助下,我的问题得到了解决。但我仍然会感谢有人告诉我上述代码有什么问题?