Skip to content

Instantly share code, notes, and snippets.

@jmsdnns
Created April 23, 2025 18:37
Show Gist options
  • Save jmsdnns/781865353d1cc684219a3a6f51cca469 to your computer and use it in GitHub Desktop.
Save jmsdnns/781865353d1cc684219a3a6f51cca469 to your computer and use it in GitHub Desktop.
Using Rust library in Ocaml

Example: Calling Rust libs from Ocaml

Create rust project and an ocaml directory.

cargo new rahst --lib
mkdir camls

Then replace everything in rahst/src/lib.rs with the following:

#[unsafe(no_mangle)]
pub extern "C" fn add(left: i32, right: i32) -> i32 {
    left + right
}

Put the following snippet in camls/main.ml:

external add : int -> int -> int = "add"

let () =
  let result = add 5 3 in
  Printf.printf "And: %d\n" result

Build Rust first, then Ocaml:

cd rahst
cargo build
cd ../camls
ocamlopt -o rsml -ccopt -L../rahst/target/debug -ccopt -lrahst main.ml
./rsml
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment