Extending C with Rust – 101

In this article I’m gonna show how to extend C code with a function written in Rust. For the sake of simplicity, let’s do it by writing a simple “hello world!”.

Setup

Initialize a new project with Cargo. I’m gonna call this one crust:

cargo new crust

Edit your Cargo.toml to make it look like this:

[package]
name = "crust"
version = "0.1.0"
authors = ["Mikolaj Wawrzyniak"]

[lib]
name = "crust"
crate-type = ["cdylib"]

We are creating a dynamic system library, so that we can load it from another language. This produces .so file on Linux, .dylib on Osx and .dll on Windows.

Rust

Open lib.rs and add the following code:

#[no_mangle]
pub extern fn hello_world() {
    println!("Hello World!");
}

The no_mangle attribute turns off Rust’s name mangling, so that it is easier to link to.

Now you can build your Rust code with

cargo build --release

This produces a file called libcrust.so in target/release/.

C

In the src directory add a new file and let’s call it crust.c.

Add following code:

void hello_world();

int main (void){
    hello_world();
}

Now build your project with gcc and link your .so file:

gcc -o crust ./src/crust.c -Isrc  -L. -l:target/release/libcrust.so

And run crust

./crust

You should see

Hello World!

written in the console.

Summary

That’s it! Next thing you could do, is to read up about the compatibility of different data types between Rust and C, so that you can write more complex code. I’d recommend this video 🙂

The code is available on my GitHub

One Comment

Comments are closed, but trackbacks and pingbacks are open.