gdal_handler.h
Go to the documentation of this file.
1
12#ifndef CCGL_DB_GDAL_H_
13#define CCGL_DB_GDAL_H_
14#ifdef USE_GDAL
15
16#include <memory>
17
18#include "gdal.h"
19#include "gdal_priv.h"
20#include <ogrsf_frmts.h>
21#include "cpl_string.h"
22#include "ogr_spatialref.h"
23
24//==================== Common: define unified types ====================//
25// Vector dataset: OGRDataSource in GDAL 1.x, GDALDataset in 2.x+
26#if GDAL_VERSION_MAJOR >= 2
27typedef GDALDataset GDALVectorDS;
28#else
29typedef OGRDataSource GDALVectorDS;
30#endif
31
32// Raster dataset: GDALDataset in all versions
33typedef GDALDataset GDALRasterDS;
34
35//==================== Vector: Open / Close ====================//
36
37inline GDALVectorDS* OpenVector(const char* path, int read_only=true) {
38#if GDAL_VERSION_MAJOR >= 2
39 GDALAllRegister();
40 int flags = GDAL_OF_VECTOR | (read_only ? GDAL_OF_READONLY : GDAL_OF_UPDATE);
41 return static_cast<GDALVectorDS*>(GDALOpenEx(path, flags, nullptr, nullptr, nullptr));
42#else
43 OGRRegisterAll();
44 return OGRSFDriverRegistrar::Open(path, read_only ? FALSE : TRUE);
45#endif
46}
47
48inline void CloseVector(GDALVectorDS* ds) {
49 if (!ds) return;
50#if GDAL_VERSION_MAJOR >= 2
51 GDALClose(ds);
52#else
53 OGRDataSource::DestroyDataSource(ds);
54#endif
55}
56
58 void operator()(GDALVectorDS* ds) const { CloseVector(ds); }
59};
60typedef std::unique_ptr<GDALVectorDS, GDALVectorDSDeleter> GDALVectorDSHandle;
61
62//==================== Raster: Open / Close / Create ====================//
63
64inline GDALRasterDS* OpenRaster(const char* path, int read_only=true,
65 const char* const* open_options=nullptr) {
66#if GDAL_VERSION_MAJOR >= 2
67 GDALAllRegister();
68 int flags = GDAL_OF_RASTER | (read_only ? GDAL_OF_READONLY : GDAL_OF_UPDATE);
69 return static_cast<GDALRasterDS*>(GDALOpenEx(path, flags, nullptr, open_options, nullptr));
70#else
71 (void)open_options; // avoid unused warnings
72 GDALAllRegister();
73 return static_cast<GDALRasterDS*>(GDALOpen(path, read_only ? GA_ReadOnly : GA_Update));
74#endif
75}
76
77inline GDALRasterDS* CreateRaster(const char* driverName, const char* filename,
78 int xsize, int ysize,
79 int bands, GDALDataType dtype,
80 char** papszOptions=nullptr) {
81 if (!driverName || !driverName[0] || !filename) return nullptr;
82 GDALAllRegister();
83 GDALDriver* drv = GetGDALDriverManager()->GetDriverByName(driverName);
84 if (!drv) return nullptr;
85 return drv->Create(filename, xsize, ysize, bands, dtype, papszOptions);
86}
87
88inline void CloseRaster(GDALRasterDS* ds) {
89 if (!ds) return;
90 GDALClose(ds);
91}
92
94 void operator()(GDALRasterDS* ds) const { CloseRaster(ds); }
95};
96typedef std::unique_ptr<GDALRasterDS, GDALRasterDSDeleter> GDALRasterDSHandle;
97#endif // USE_GDAL
98#endif // CCGL_DB_GDAL_H_
Definition: gdal_handler.h:93
Definition: gdal_handler.h:57