#ocaml #gen #bindings


A library for generating OCaml code

1 unstable release

Uses new Rust 2021

0.1.0 Sep 12, 2022

#4 in #ocaml

Download history 25/week @ 2022-09-11 6/week @ 2022-09-18 512/week @ 2022-09-25 773/week @ 2022-10-02 1253/week @ 2022-10-09 1396/week @ 2022-10-16 1552/week @ 2022-10-23 1873/week @ 2022-10-30 1410/week @ 2022-11-06 2387/week @ 2022-11-13 1033/week @ 2022-11-20

6,724 downloads per month


495 lines


This crate provides automatic generation of OCaml bindings. Refer to the rustdoc for more information.

Binding generation

Here's an example of generating some bindings:

// initialize your environment
let env = &mut Env::default();

// choose where you want to write the bindings
let w = &mut std::io::stdout();

// we need to create fake generic placeholders for generic structs
decl_fake_generic!(T1, 0);
decl_fake_generic!(T2, 1);

// you can declare modules
decl_module!(w, env, "Types", {
    // and types
    decl_type!(w, env, SomeType);

    // and even generic types
    decl_type!(w, env, SomeGenericType::<T1>);

    // you can also rename a type
    decl_type!(w, env, SomeOtherGenericType::<T1> => "thing");

decl_module!(w, env, "ImportantType", {

    // the OCaml way is often to rename your module's main type as `t`
    decl_type!(w, env, CamlBigInteger256 => "t");

    // you can declare functions as well
    // note that the underlying function calls `caml_of_numeral_to_ocaml`
    // so you have to either import all (e.g. `use path::*`)
    // or you have to import `caml_of_numeral_to_ocaml`
    decl_func!(w, env, caml_of_numeral => "of_numeral");

Binding description

To allow the previous example to work, you must derive the correct functions on your types and functions. To do that, you can use the ocaml-gen-derive crate.

To allow generation of bindings on structs, use Struct:

struct MyType {
  // ...

To allow generation of bindings on enums, use ocaml_gen::Enum:

enum MyType {
  // ...

To allow generation of bindings on functions, use ocaml_gen::func:

#[ocaml::func] // if you use the crate ocaml-rs' macro, it must appear after
pub fn your_function(arg1: String) {

To allow generation of bindings on custom types, use ocaml_gen::CustomType:

struct MyCustomType {
  // ...


  • ocaml-gen: the tool that allows us to generate the OCaml bindings from the Rust code.
  • ocaml-gen-derive: derive macros have to be a in separate crate, so they are here. This crate is re-exported by ocaml-gen so end users should not have to worry about it.
  • tests/: contains some tests. If you are looking for examples on how to use ocaml-gen, you can check that folder.

Additional resources

you can check the recording I made when I first introduced the tool internally.


~28K SLoC