Transpiling C dependencies using Ocaml's C headers

Hello!

I’m transpiling an OCaml project to JavaScript using js_of_ocaml, but my project depends on C/C++ files that use OCaml’s C headers (e.g., from <caml/memory.h>, CAMLparam for argument handling, CAMLreturn for returning values).

Is there a way to transpile these C/C++ files to JavaScript or WebAssembly?

I’ve looked into Emscripten, but I get stuck at the linking stage since there’s no corresponding compiled C object to go with the headers. Ideally, I’d like to find a solution that doesn’t require modifying the existing C/C++ code.

Any guidance would be greatly appreciated!

Hello,

These headers are part of the runtime system of OCaml. When executing code produced by js_of_ocaml it is the JS runtime that is used instead so transpiling these files into JS is unlikely to be of much use.

The standard way to deal with C primitives when using js_of_ocaml is to reimplement the C primitives in JS (using the same name) and link them with the rest of your application; js_of_ocaml will automatically use them to resolve the externals in your program.

See Link with JavaScript code for the details.

Cheers,
Nicolas

We know how it could be done in Wasocaml without the need to change the OCaml FFI so existing programs written in OCaml+C could work out of the box. But I can’t tell when this will be implemented.

Do you have any resources or references that could help me try implementing this myself?
Rewriting C primitives in JavaScript isn’t really an option.

The idea is very briefly described in my thesis (in french).

But to get something usable someone has to:

  • complete the implementation of the runtime in Wasocaml (this is very tedious);
  • write a new version of the OCaml headers where you replace the definition of the various macros to make them compatible with the Wasm runtime (also, you’ll probably get some issues with Field being used as an l-value, in this case you’ll have to rewrite the C file to use a Set_field primitive or something similar);
  • understand how to talk to clang to get the C files compiled correctly;
  • integrate all of this in the build system.

This is something we’ll eventually do when porting Wasocaml to Flambda2 but this won’t happen in the short term as I am currently working full-time on cross-language symbolic execution in Owi.

1 Like