So I have been doing a lot of Python and Django lately, but I miss Go. As an experiment I wanted to see how difficult it would be to directly call Golang functions from Python using my favourite build tool Bazel.

I found this post, which explains how to build and connect the two manually:

Python and Go : Part II - Extending Python With Go

Great now I am like 90% there!

So all you need is a Golang file main.go: package main import "C" import "fmt" //export hello func hello(inputC *C.char) *C.char { input := C.GoString(inputC) return C.CString(fmt.Sprintf("Hello %s", input)) } func main() {}

This just defines a method that accepts a C type and tags it to be exported.

The Python code looks like main.py: import ctypes so = ctypes.cdll.LoadLibrary('./_golib.so')``hello = so.hello hello.argtypes = [ctypes.c_char_p] hello.restype = ctypes.c_void_p``free = so.free free.argtypes = [ctypes.c_void_p]``ptr = hello('World'.encode('utf-8')) out = ctypes.string_at(ptr) free(ptr)``print(out.decode('utf-8'))

This code loads the Golang library, defines the method to call (and its free method that comes free with Golang lib), calls it, which prints out Hello World

The only special Bazel code is: go_library( name = "project_lib", srcs = ["main.go"], **cgo = True,** importpath = "github.com/grahamjenson/bazel-python-to-golang", )``go_binary( name = "project", embed = [":project_lib"], **linkmode="c-shared", out="_golib.so"** )

Setting the cgo and linkmode args, and writing the output file to a library name.

I thought this post would be longer, but it turns out to be super easy!

image Wellington