DEV Community

Mustafif
Mustafif

Posted on

Using Zig in Rust!

In my head I thought hey how would I go about integrating Zig and Rust together in a sorta simple way, and then it came to me...they both use FFI for C interoperability. So if I would compile a Zig file as a dynamic library and link it to my Rust program treating is a C shared library, we're good to go right? I was happy to find out it does work...

Let's create a simple zig file called mylib.zig with the following add function that's exported to C.

const std = @import("std");

export fn zig_add(a: i32, b: i32) i32 {
    return a + b;
}
Enter fullscreen mode Exit fullscreen mode

Let's now create a Rust file, main.rs that will have an extern block that will declare our zig_add function and in our main function we will use it, taking note that when using zig_add we will have to wrap it in an unsafe block.

extern "C" {
    fn zig_add(a: i32, b: i32) -> i32;
}

fn main() {
    let result = unsafe { zig_add(1, 2) };
    println!("1 + 2 = {}", result);
}
Enter fullscreen mode Exit fullscreen mode

In our example we will be using a Linux system because of the ease with C development on it, and the fact that we will need environment variables to set our linker path. Now let's see how we can have these files work with eachother.

# compile zig file as dynamic library 
$ zig build-lib mylib.zig -dynamic 
# compile rust file linking our library 
$ rustc main.rs -L . -l mylib 
# set the linker path 
$ export LD_LIBRARY_PATH=./
$ ./main 
1 + 2 = 3
Enter fullscreen mode Exit fullscreen mode

For those wondering, if we didn't set the linker path, we would get the following error:

./main: error while loading shared libraries: libmylib.so: cannot open shared object file: No such file or directory
Enter fullscreen mode Exit fullscreen mode

Top comments (0)