Skip to content

tizoc/ocaml-interop

Repository files navigation

ocaml-interop

build crate documentation license

Zinc-iron alloy coating is used in parts that need very good corrosion protection.

API IS CONSIDERED UNSTABLE AT THE MOMENT AND IS LIKELY TO CHANGE IN THE FUTURE

IMPORTANT: Starting with version 0.11.0 only OCaml 5.x is supported

ocaml-interop is an OCaml<->Rust FFI with an emphasis on safety inspired by caml-oxide, ocaml-rs and CAMLroot.

Read the API reference and documentation here.

Report issues on Github.

A quick taste

Convert between plain OCaml and Rust values

let rust_string = ocaml_string.to_rust();
// `cr` = OCaml runtime handle
let new_ocaml_string = rust_string.to_ocaml(cr);

Convert between Rust and OCaml structs/records

(* OCaml *)
type my_record = {
  string_field: string;
  tuple_field: (string * int64);
}
// Rust
#[derive(ToOCaml, FromOCaml)]
struct MyStruct {
    string_field: String,
    tuple_field: (String, i64),
}

// ...

let rust_struct = ocaml_record.to_rust();
let new_ocaml_record = rust_struct.to_ocaml(cr);

Convert between OCaml and Rust variants/enums

(* OCaml *)
type my_variant =
  | EmptyTag
  | TagWithInt of int
// Rust
#[derive(ToOCaml, FromOCaml)]
enum MyEnum {
    EmptyTag,
    TagWithInt(#[ocaml(as_ = "OCamlInt")] i64),
}

// ...

let rust_enum = ocaml_variant.to_rust();
let new_ocaml_variant = rust_enum.to_ocaml(cr);

Call OCaml functions from Rust

(* OCaml *)
Callback.register "ocaml_print_endline" print_endline
// Rust
ocaml! {
    fn ocaml_print_endline(s: String);
}

// ...

ocaml_print_endline(cr, "hello OCaml!");

Call Rust functions from OCaml

#[ocaml_interop::export]
pub fn twice_boxed_int(cr: &mut OCamlRuntime, num: OCaml<OCamlInt64>) -> OCaml<OCamlInt64> {
    let num = num.to_rust();
    let result = num * 2;
    result.to_ocaml(cr)
}
(* OCaml *)
external rust_twice_boxed_int: int64 -> int64 = "twice_boxed_int"

(* ... *)

let result = rust_twice_boxed_int 123L in
(* ... *)

References and links

About

OCaml<->Rust FFI with an emphasis on safety.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Contributors 9

Languages