Extend Python and C with
Go Using Pybind and
Cython
Rihab Sakhri
Why Extend Python or C with Go?
Python: Amazing for data processing and prototyping but
struggles with heavy computations.
C : Super fast, but... writing clean, maintainable C code? Painful,
right?
Go : A perfect middle ground, easy to write, fast and highly
portable!
When you combine all three, you get:
Friendly interface for users and prototyping.
Hardcore speed for specialized, low-level tasks.
The glue that bridges performance and simplicity.
Rihab Sakhri
How to Extend Python with Go?
Go can compile into shared libraries (.so files) that
Python can call using tools like ctypes.
Example: Calling Go from Python
Step 1: Write Go Code
{ the export directive makes
the Multiply function
accessible to external
languages.
Rihab Sakhri
Step 2 : Compile Go to a Shared Object
Bash
go build -buildmode=c-shared -o libmath.so main.go
This creates a libmath.so file (a shared
object) that ca n be used in P ython.
Rihab Sakhri
Step 3 : Call It in Python
Done
You’ve successfully extended Python with Go.
Rihab Sakhri
How to Extend C with Go ?
Go can also act as a back-end for C code, simplifying
C projects by offloading complex logic to Go.
Example: Using Go in a C Project
Step 1: Write Go Code
{ Add function from Go to
be called by C code.
Rihab Sakhri
Step 2: Compile Go to a Shared Library
Bash
go build -buildmode=c-shared -o libmath.so main.go
This creates a libmath.so file (a shared
library) that can be used in C .
Rihab Sakhri
Step 3: Write a C Program
Rihab Sakhri
Step 4: Compile and Run the C Code
Bash
gcc -o main main.c -L. -lmath./main
This command compiles the main.c
program and links it with the libmath.so
shared library, which was generated from
the Go code.
Rihab Sakhri
Why You’ll Love This Approach ?
Go adds concurrency and speed to Python and simplifies C
workloads.
Go’s simple syntax reduces the complexity of large C projects.
Build Go libraries that work seamlessly with Python and C.
Your Go libraries can be reused across multiple projects and
languages.
Some places where this combination adds value :
Data Science: Write performance-critical algorithms in Go and expose
them to Python.
Game Development: Use Go for game logic while keeping Python for
scripting and C for rendering.
Microservices: Develop Go-based libraries and use Python as the API
layer
Rihab Sakhri
Important Notes
Go handles its own garbage collection, but Python
objects passed to Go must be carefully managed to avoid
memory leaks.
Ensure no circular references when exchanging data.
Go runtime must initialize before calling exported
functions. Ensure the Go main function is part of the
library to initialize the runtime.
Only functions with the //export directive will be visible
outside the Go library.
Be cautious with segmentation faults, which often occur
due to incompatible data types or memory
mismanagement.
Rihab Sakhri