DEV Community

Tony Colston
Tony Colston

Posted on

call Zig from Python

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;
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
tythos profile image
Brian Kirkpatrick

Can't <3 this enough; amazing how straightforward this is, and I really appreciate how ctypes.CDLL (unlike cffi) doesn't require we define an inline header symbol.