Inlining C code in OCaml

A great thing about OCaml is the possibility of creating bindings with C. The bad thing about it is that it's a pain to do. Olivier and I are currently thinking about a way to make that less painful. Here is a first draft : inlining C code in OCaml, in order to avoir multiple files.

Using camlp4, we extract the quotations containing C code and we dump that in a temporary .c file, and compile it. Here is an example:

<:c<
#include <caml/mlvalues.h>
#include <caml/memory.h>
#include <caml/alloc.h>
#include <caml/custom.h>
>>

external add: int -> int -> int = "add"
<:c<
value add(value a, value b) {
  int c;
  CAMLparam2(a,b);
  c = Int_val(a) + Int_val(b);
  CAMLreturn(Val_int(c));
}
>>

let _ =
  Printf.printf "La réponse est %d\n%!" (add 21 21);

The thing we would like to do is the following:

let add a b = <:cfun<
  int c = Int_val(a) + Int_val(b);
  CAMLreturn(Val_int(c));
>>

Which would be converted to:

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

value add (value a, value b) {
  CAMLparams2(a,b);
  int c = Int_val(a) + Int_val(b);
  CAMLreturn(Val_int(c));
}

Downloaded : 107 times
File : inlinec.tar.gz
Size: 732 o

4 Responses to "Inlining C code in OCaml"

olivier says:

En fait, ce qu’on aimerait faire, c’est plutôt ça

let add a b = <:cfun<
int c = a + b;
return c;
>>

Si on trouve un moyen de récupérer le type et les arguments, on peut mettre les Int_val autour de a et b automatiquement.

Pareil pour le CAMLreturn, on peut le rajouter et ça évite à l’utilisateur de se plonger dans le _Développement d’applications avec Objective Caml_.

olivier says:

Quand je dis rajouter, ça peut se faire assez facilemetn avec le préprocesseur de c, des trucs du genre :

#define a Int_val(a)

C'est un peu plus compliqué avec le return, je ne suis pas sûr qu'on puisse remplacer des choses de la forme "return c" mais c'est pas grave, il suffit d'un wrapper autour.

kordial says:

Bonjour, ne serait il pas possible d'interfacer oCaml avec C? En clair, d'écrire dans un environnement C, mais en faisant appel en cas de besoin à ses modules oCaml?
(la question me taraude depuis un moment et c pas faute d'avoir cherché, mais je trouve rien de concret là dessus)
Merci!

Leave a Reply