Simple example of calling Rust from Julia


I was asked for a simple example about how to call Rust from Julia on Slack. I thought I would post it here for posterity.

Just to emphasize, my goal here is simplicity. For practical use, you would probably want to use cargo with jlrs. That said, I do find some virtue in simple and reductionist demonstrations.

The code

pub extern "C" fn rust_add(a: i64, b: i64) -> i64 {
    return 2*a + 3*b


const libpath = "./"
hellorust(a, b) = @ccall libpath.rust_add(a::Int64, b::Int64)::Int64
@info "From Julia: " hellorust(2,3)

Compile and Execute

To compile and execute run the following from your favorite shell.

$ rustc --crate-type=cdylib

$ julia hellorust.jl 
┌ Info: From Julia: 
└   hellorust(2, 3) = 13

$ ls  hellorust.jl


Rust and Julia both know how to interact with C. On the Rust side we export a C callable function called rust_add. On the Julia side, we call that C function via ccall.

Smaller Rust binaries

I was asked on Twitter how to make the Rust binary smaller. We can optimize and strip the debugging symbols.

$ rustc --crate-type=cdylib

$ du -h 

$ rustc --crate-type=cdylib -O

$ du -h 

$ strip 

$ du -h