Golang binaries in Python

Dawid Laszuk published on
1 min, 128 words

To use golang binaries in Python, one can do that by first converting golang programs into shared libraries and then calling them from Python. This can be done by using the cgo package in golang. The following is an example of how to do this:

package main

import "C"

//export Add
func Add(a, b int) int {
    return a + b
}

func main() {}

The above code can be compiled into a shared library by running the following command:

go build -buildmode=c-shared -o libadd.so add.go

The shared library can then be called from Python by using the ctypes package. The following is an example of how to do this:

from ctypes import cdll

lib = cdll.LoadLibrary('./libadd.so')
lib.Add.argtypes = [ctypes.c_int, ctypes.c_int]
lib.Add.restype = ctypes.c_int

print(lib.Add(1, 2))