Simple example of calling Rust from Julia

Introduction

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

hellojulia.rs:

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

hellorust.jl

const libpath = "./libhellojulia.so"
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 hellojulia.rs --crate-type=cdylib

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

$ ls
hellojulia.rs  hellorust.jl  libhellojulia.so

Explanation

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 hellojulia.rs --crate-type=cdylib

$ du -h libhellojulia.so 
3.6M	libhellojulia.so

$ rustc hellojulia.rs --crate-type=cdylib -O

$ du -h libhellojulia.so 
3.3M	libhellojulia.so

$ strip libhellojulia.so 

$ du -h libhellojulia.so 
16K	libhellojulia.so
21 Likes