# Simple example of calling Rust from Julia

**URL:** <https://discourse.julialang.org/t/simple-example-of-calling-rust-from-julia/111742>\
**Category:** General Usage\
**Created:** [March 18, 2024, 3:31am UTC](https://discourse.julialang.org/t/simple-example-of-calling-rust-from-julia/111742 "2024-03-18T03:31:57Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![mkitti](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mkitti/32/12459_2.png) [@mkitti](https://discourse.julialang.org/u/mkitti)\
**Post date:** [March 18, 2024, 3:31am UTC](https://discourse.julialang.org/t/simple-example-of-calling-rust-from-julia/111742/1 "2024-03-18T03:31:57Z")

</div>

## 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`](https://discourse.julialang.org/t/jlrs-v0-19-many-performance-optimizations/102253). That said, I do find some virtue in simple and reductionist demonstrations.

## The code

hellojulia.rs:

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

```

hellorust.jl

```julia
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.

```julia-auto
$ 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`](https://docs.julialang.org/en/v1/manual/calling-c-and-fortran-code/).

## Smaller Rust binaries

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

```julia-auto
$ 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

```
