Last active
January 17, 2016 18:56
-
-
Save schoenobates/940ca67b93783d1aa5f4 to your computer and use it in GitHub Desktop.
Example of using OGR APIs from Go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
/* | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include "gdal_version.h" | |
#include "ogr_api.h" | |
#cgo darwin pkg-config: gdal | |
#cgo linux pkg-config: gdal | |
*/ | |
import "C" | |
import ( | |
"fmt" | |
"os" | |
"unsafe" | |
) | |
func main() { | |
if len(os.Args) == 1 { | |
fmt.Println("No file specified") | |
os.Exit(128) | |
} | |
fmt.Printf("GDAL: Version = %d.%d.%d, Version Num = %d, Build = %d, Release Date = %d, Release Name = %s\n", | |
C.GDAL_VERSION_MAJOR, | |
C.GDAL_VERSION_MINOR, | |
C.GDAL_VERSION_REV, | |
C.GDAL_VERSION_NUM, | |
C.GDAL_VERSION_BUILD, | |
C.GDAL_RELEASE_DATE, | |
C.GDAL_RELEASE_NAME, | |
) | |
C.OGRRegisterAll() | |
var hds C.OGRDataSourceH | |
var dsname = C.CString(os.Args[1]) | |
hds = C.OGROpen(dsname, 0, nil) | |
C.free(unsafe.Pointer(dsname)) | |
if hds == nil { | |
fmt.Printf("Failed to open dataset: %s", os.Args[1]) | |
os.Exit(129) | |
} | |
defer func() { | |
C.OGR_DS_Destroy(hds) | |
}() | |
count := C.OGR_DS_GetLayerCount(hds) | |
if int(count) == 0 { | |
fmt.Println("no layers found in dataset") | |
os.Exit(129) | |
} | |
layer := C.OGR_DS_GetLayer(hds, C.int(0)) | |
C.OGR_L_ResetReading(layer) | |
for { | |
feature := C.OGR_L_GetNextFeature(layer) | |
if feature == nil { | |
break | |
} | |
geom := C.OGR_F_GetGeometryRef(feature) | |
if geom != nil { | |
c_ptr := C.OGR_G_ExportToJson(geom) | |
json := C.GoString(c_ptr) | |
C.free(unsafe.Pointer(c_ptr)) | |
fmt.Println(json) | |
} | |
C.OGR_F_Destroy(feature) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment