DEV Community

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

Posted on

1 1

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!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay