DEV Community

Cover image for Building a Python wrapper of C libgeohash using CFFI
Aldrin Navarro
Aldrin Navarro

Posted on

Building a Python wrapper of C libgeohash using CFFI

First post for DEV.TO 🎊️

I didn't know what a Geohash is before and was blown away by it's concept. I found an implementation of it written in C. Well I always have been wanting to experiment with foreign functions and found CFFI suitable for my case. On that same afternoon I wrote a simple wrapper of libgeohash in Python.

Check this out! https://aldnav.com/blog/writing-a-geohash-wrapper-using-cffi/
What's that? Want to jump in to the source code instead? Ok! https://github.com/aldnav/geohash

Here's a preview.

# geohash_build.py
from cffi import FFI
ffi = FFI()
ffi.cdef(
    """
    char* geohash_encode(double lat, double lng, int precision);
    GeoCoord geohash_decode(char* hash);
"""
)
lib = ffi.dlopen("geohash.so")
ffi.set_source("_geohash", None)
Enter fullscreen mode Exit fullscreen mode
# Simple testing
from _geohash import ffi, lib
print(lib.geohash_encode(35.689487, 139.691706, 6))
#>> xn774c
Enter fullscreen mode Exit fullscreen mode
# Use geohash module
import geohash
geohash.geohash_encode(48.856614, 2.352222)  # u09tvw for Paris! 
geohash.geohash_decode("wy7b1h")  # lat: 35.179554, long: 129.075642
Enter fullscreen mode Exit fullscreen mode

Check my notes to see how I build the wrapper. Plus some more references that links to more comprehensive notes from the respective authors.

Let me know your thoughts!

Oldest comments (0)