OCaml / Rust Interop

Besides "just use C FFI" does anyone have a good tutorial for:

  1. OCaml <-> Rust Interop
  2. OCaml Rep <-> Rust Interop

I'm a big fan of the Rust language, but sometimes I'm really wishing I had a REPL where I could create a few objects, call a few trait functions, and send a few objects to some mpsc::Channels.

Of all the languages to interop with Rust, OCaml seems the nicest. Suggestions?

There is ::ocaml, a fork of ::raml for direct ffi bindings between Rust and Ocaml (no C stubs).

::ocaml also comes with an experimental ::derive-ocaml, for some syntactic sugar.

I don't know how "smooth" the interop experience is, though.

@zshipko : GitHub - zshipko/ocaml-rs: OCaml extensions in Rust looks amazing.

I would like to achieve the following. Can you provide guidance of roughly what to do:

  1. At https://github.com/zshipko/ocaml-rs/tree/master/example/src you have sample code where (a) Rust side uses caml! macro and (b) OCaml side has some type signatures. There's also a dune file -- so that when we run "dune utop", we can then call the Rust functions.

  2. Is there a way to do the above with an OCaml REPL embedded in a Rust app? I want a situation where (1) the Rust app starts running (2) it opens up some TCP port, say 8888 -- and (3) offers me an OCaml REPL (with lots of Rust functions) on that port.

  3. Is there a way to make this work with wasm32? I want a situation where: I have a webapp written in Rust, but then it opens a textarea ... and gives me an OCaml REPL (with lots of exported Rust functions).


Unfortunately OCaml doesnt provide a straightforward way of dropping into a REPL, however maybe this approach will work for you.

I'm not really familiar with the WASM stuff so someone else will have to touch on that.

1 Like

@zshipko : Thanks for clarifying the boundary/cutting-edge of what currently works / doesn't work!

Using the Toploop or Optoploop ocaml modules as suggested by @zshipko should work fine to have access to a toplevel.
That's actually what utop or the jupyter ocaml kernel are using. I don't have a tutorial at hand but would suggest looking at eval_phrase in this file from the jupyter kernel. I recently worked on this to allow python code to call the ocaml top-level and this worked fine, hopefully the result will be released as open-source in the near future.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.