package main
import "C"
import (
"fmt"
"log"
"github.com/peterstace/simplefeatures/geom"
"github.com/twpayne/go-geos"
)
//export Add
func Add(a, b int) int {
return a + b
}
//export GeomZDiff
func GeomZDiff(geomWkt *C.char) C.float {
goGeomWkt := C.GoString(geomWkt)
if goGeomWkt == "" {
fmt.Println("geomWkt 为空")
return C.float(0)
}
// 使用 WKT 解析器解析 WKT 字符串
geom, err := geos.NewGeomFromWKT(goGeomWkt)
if err != nil {
fmt.Println("Error reading WKT:", err)
return C.float(0)
}
if geom.TypeID() != geos.TypeIDLineString {
fmt.Println("Geometry is not a LineString")
return C.float(0)
}
if !geom.IsValid() {
return C.float(0)
}
// 获取 LineString 的坐标
coordSeq := geom.CoordSeq()
coords := coordSeq.ToCoords()
maxZ := coords[0][2]
minZ := coords[0][2]
for i := 1; i < len(coords); i++ {
if coords[i][2] > maxZ {
maxZ = coords[i][2]
}
if coords[i][2] < minZ {
maxZ = coords[i][2]
}
}
return C.float(maxZ - minZ)
}
//export GeomZDiff2
func GeomZDiff2(geomWkt *C.char) C.float {
goGeomWkt := C.GoString(geomWkt)
if goGeomWkt == "" {
fmt.Println("geomWkt 为空")
return C.float(0)
}
geom, err := geom.UnmarshalWKT(goGeomWkt)
if err != nil {
log.Fatalf("Failed to unmarshal WKT: %v", err)
return C.float(0)
}
lineString, ok := geom.AsLineString()
if !ok {
return C.float(0)
}
err = lineString.Validate()
if err != nil {
return C.float(0)
}
coords := lineString.Coordinates()
maxZ := coords.Get(0).Z
minZ := coords.Get(0).Z
for i := 1; i < coords.Length(); i++ {
c := coords.Get(i)
if c.Z > maxZ {
maxZ = c.Z
}
if c.Z < minZ {
maxZ = c.Z
}
}
return C.float(maxZ - minZ)
}
func main() {
// wkt := "LINESTRING Z(116.21126367 39.86818626 0.0000011, 116.21167992 39.86805255 0.00005, 116.21143061 39.86831677 0.00005, 116.21125012 39.86857083 0.00005)"
// // wkt2 := "MULTILINESTRING ((0 0, 1 1), (0 0, 1 1))"
// fmt.Println(GeomZDiff2(wkt))
}
// go build -o mylib.so -buildmode=c-shared mylib.go
import cffi
# 初始化 CFFI
ffi = cffi.FFI()
# 定义函数原型
ffi.cdef("""
float GeomZDiff2(const char* geomWkt);
float GeomZDiff(const char* geomWkt);
""")
# 加载共享库
C = ffi.dlopen("./mylib.so")
# 示例调用
# geom_wkt = "LINESTRING Z (30 10 5, 10 30 15, 40 40 10)"
geom_wkt = ""
z_diff = C.GeomZDiff2(geom_wkt.encode('utf-8'))
print("Z Difference:", z_diff)
z_diff = C.GeomZDiff(geom_wkt.encode('utf-8'))
print("Z Difference:", z_diff)