Embedding Python & GoLang Codes Each Other

Embedding Python in GoLang

Introducing CGO

Cgo enables the creation of Go packages that call C code. Cgo is not a language nor a compiler. It’s a Foreign Function Interface (FFI), a mechanism we can use in Go to invoke functions and services written in a different language, specifically C. Here is a simple example using:

Embedding CPython

We can access the CPython interpreter by CGO library in Golang. Because Python supports C API to can embed “C” codes like Golang. So a Go program that, technically speaking, embeds CPython is not as complicated as you might expect.


// #cgo pkg-config: python-2.7
package main

// #cgo pkg-config: python-2.7
import (
python "github.com/sbinet/go-python"

func main() {
python.PyRun_SimpleString("print 'hello, world!'")
package mainimport "github.com/DataDog/go-python3"

func main() {
defer python3.Py_Finalize()
python3.PyRun_SimpleString("print('hello world')")

Embedding GoLang in Python

Build Go package as C shared library or object

Every Go the main package can be built as a C shared library. Any C shared library can be distributed, installed, and linked to every C application and applications in other programming languages that can reference C shared libraries.

go build -o main.so -buildmode=c-shared main.go

Some Notes About Shared Objects

“.so” file extension is a standard for shared library objects. It is not compulsory but it is conventional in Linux/Unix Systems. It is “.dll” is the same meaning in Windows Systems.
There is a global environment named “LD_LIBRARY_PATH” in Linux System for searching shared objects. Our code did not raise errors because of setting the exact location.

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/batur/lib



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store