DEV Community

loading...

call Zig from Python

Tony Colston
wanna be gamedev ... all around nerd and dev
・1 min read

What is Zig? See here: https://ziglang.org/

Looks interesting!

Lets make a shared library with Zig that we can call with Python using ctypes.

export fn add(a : i32, b : i32) i32 {
  return a + b;
}

The code above is a function named add that takes two parameters both of type integer (32 bits). The function returns a 32 bit integer also.

To compile this to dynamic library run this

zig build-lib mathtest.zig -dynamic

At this point you will have a shared library in your current directory.

-rw-r--r-- 1 tonetheman tonetheman     58 Sep  3 07:28 mathtest.zig
-rw-r--r-- 1 tonetheman tonetheman 546152 Sep  3 07:35 mathtest.o
-rw-r--r-- 1 tonetheman tonetheman    395 Sep  3 07:35 mathtest.h
-rwxr-xr-x 1 tonetheman tonetheman 616728 Sep  3 07:35 libmathtest.so.0.0.0

Notice also you get some other files for free, most notably the header file mathtest.h. You could use this file with a C/C++ compiler to also call the Zig function.

Fire up your Python interpreter and see if you can call your first Zig function.

>>> import ctypes
>>> a = ctypes.CDLL("./libmathtest.so.0.0.0")
>>> print(a)
<CDLL './libmathtest.so.0.0.0', handle 58bfef25b470 at 78bf0457bf10>
>>> a.add(400,400)
800

Discussion (0)