package camlid
Camlid
Camlid generates the C stubs and the OCaml externals binding a C library, from a description of its functions written in OCaml. Compared to camlidl the description is an OCaml program, so it is easy to extend (see Expert). Compared to ctypes the C data structures are manipulated in C, by generated C code, which simplifies the build.
The tests directory contains standalone examples with their generated files.
Quickstart
To bind the functions of alib.h:
void f_input(int);
void f_output(int *);
int f_with_res();
void f_no_arg_no_result();write a generator in a generator sub-directory, with the dune file:
(executable (name generator) (libraries camlid))and generator.ml:
open Camlid
open Helper
let () =
Generate.to_file "mylib" ~headers:[ "alib.h" ]
[
func "f_input" [ input c_int ];
func "f_output" [ output (ptr_ref c_int) ];
func "f_with_res" [] ~result:c_int;
func "f_no_arg_no_result" [];
]func "name" params describes the C function name. Each parameter says whether the argument of the C function is an Camlid.Helper.input or an Camlid.Helper.output of the OCaml function, and gives its type. A type describes the OCaml type, the C type, the conversions, and the memory to allocate and free. Here Camlid.Helper.c_int is an OCaml int and a C int; Camlid.Helper.ptr_ref gives to f_output a pointer to an int to fill. The generated OCaml functions are:
val f_input : int -> unit
val f_output : unit -> int
val f_with_res : unit -> int
val f_no_arg_no_result : unit -> unitIn the dune file of the library, generate and compile the stubs:
(rule
(targets mylib_stub.c mylib.ml)
(action (run %{exe:generator/generator.exe}))
(mode (promote (until-clean))))
(library
(public_name mylib)
(foreign_stubs
(language c)
(names mylib_stub alib)
(flags :standard -Werror=implicit-function-declaration -std=c11)))The (promote (until-clean)) mode lets you see the generated files in the source directory. Don't use (mode promote): the files would not be regenerated in release mode, and they depend on the version of OCaml. Camlid is not a dependency of the library.
Memory
The C value of a parameter lives in a local variable of the stub, and follows the lifecycle of a C++ object:
- input: it is converted from the OCaml value (
ml2c); - not an input: it is initialized by its constructor (
init); - the C function is called;
- output: it is converted to an OCaml value (
c2ml); - it is destroyed by its destructor (
free).
There are two kinds of types, depending on who owns the C data (Camlid.Ty.contract.owned_by_ml):
the conversions | the destructor | examples | |
|---|---|---|---|
copied | copy the data between OCaml and C | frees the C copy | scalars, strings, arrays, |
owned by OCaml |
| none, the finalizer of the OCaml value frees it | custom blocks, bigarrays, |
So, for a type owned by OCaml, the C function can modify an input in place, and a parameter can't be both an input and an output: the C data would be owned by two OCaml values. An OCaml value never refers to memory owned by C: such a pointer is copied (see copy_of_ptr below).
For copied types with allocated memory (strings and arrays), ~owned:false removes the destructor: the C function takes ownership of an input, or keeps ownership of an output (e.g. a static string).
C++-like types
Many C libraries (GMP, FLINT, ...) handle their types like C++ classes, with a constructor, a destructor and a copy function. Camlid.Helper.value_type binds such a type once, for the three ways a C function can use it:
(* void vec_init(vec *v); void vec_clear(vec *v); void vec_set(vec *dst, vec *src); *)
let vec =
value_type ~init:"vec_init" ~clear:"vec_clear" ~copy:"vec_set"
~ml:"vec" ~c:"vec" ()
let () =
Generate.to_file ~headers:[ "lib.h" ] "mylib"
[
(* void vec_range(vec *, size_t); *)
func "vec_range" [ output vec.t; input size_t ];
(* void vec_push(vec *, intptr_t); modifies the OCaml value in place *)
func "vec_push" [ input vec.t; input int ];
(* void vec_ranges(vec *, size_t); fills an array of vec *)
(let a = fixed_length_array ~len_used_in_call:true vec.value in
func "vec_ranges" [ a.t; a.len ]);
(* vec *vec_global(void); returns a vec owned by C *)
func "vec_global" [] ~result:vec.copy_of_ptr;
]vec.tis avec *owned by OCaml: an output is allocated and initialized by the stub, then owned by the OCaml value whose finalizer clears and frees it;vec.valueis aveccopied from or to avecowned by OCaml, and cleared by the stub;vec.copy_of_ptris avec *owned by C, copied into avecowned by OCaml.
When the constructor needs arguments, they can come from an Camlid.Helper.extra_input, an argument of the OCaml function not given to the C function:
(* void mat_init(mat *, intptr_t rows, intptr_t cols); *)
let rows, rows_var = extra_input ~label:"rows" int
let cols, cols_var = extra_input ~label:"cols" int
let mat =
value_type ~init:"mat_init" ~init_args:[ rows_var; cols_var ]
~clear:"mat_clear" ~copy:"mat_set" ~ml:"mat" ~c:"mat" ()
(* val zero : rows:int -> cols:int -> mat *)
let zero = func "mat_zero" ~ml:"zero" [ output mat.t; rows; cols ]Parents and children
A C value often depends on another one: a statement on its database, a node on its manager. Camlid.Helper.keep_alive stores the OCaml value of the parent with the child, so the parent stays alive while the child is used. When the parent is also needed to destroy the child, Camlid.Helper.parent and Camlid.Helper.child count the references to the parent, which is destroyed after its last child:
(* node *node_new(db *d, intptr_t i); void node_free(db *d, node *n); *)
let db, db_parent = parent ~clear:"db_close" ~ml:"db" ~c:"db *" ()
let node = child db_parent ~clear_with_parent:"node_free" ~ml:"node" ~c:"node *" ()
let node_new =
let d, _, d_ml = Expert.param ~input:true ~name:"d" db in
func "node_new" [ d; input int ] ~result:(node.with_parent d_ml)Errors, runtime lock and noalloc
The stub raises an exception only when it owns nothing, or after cleaning up: the conversions themselves never raise. A type that refuses some values has a check (Camlid.Ty.checks), a C condition evaluated before its conversion: string_nt refuses strings with null bytes, enum unknown C constants, dispose disposed values. The checks of the inputs run before any conversion; the checks of the outputs and ~error run after the call, and clean up before raising (copies are freed, outputs owned by OCaml are moved into OCaml values and finalized later).
~error checks the result of the C function after the call:
(* int make(vec *, char **, intptr_t n); returns a negative code on failure
int is_error(int rc, intptr_t n); const char *msg(int rc, intptr_t n); *)
let my_error = exception_ ~registered:"Mylib.My_error" "My_error"
let make =
let n, n_var = Expert.simple_param ~input:true ~name:"n" int in
func "make" ~ignored_result:c_int
~error:(error ~exn:my_error ~msg:"msg" ~vars:[ n_var ] "is_error")
[ output vec.t; output (ptr_ref (string_nt ())); n ]When the conversions don't allocate in the OCaml heap (scalars, inputs owned by OCaml, ...), there is no check, and there is at most one result, the external is declared [@@noalloc] and the stub doesn't register its values with CAMLparam. Use ~noalloc:false if the C function calls the OCaml runtime itself.
The order of the steps of a stub, the values registered with the GC and these decisions are made by Camlid.Plan.schedule, which is proved in Why3 to be memory safe (proof/schedule.mlw), provided that each type matches its Camlid.Ty.contract and that the model of the memory, still very abstract (proof/spec.mlw), is faithful to C and to the OCaml runtime. This proof is a work in progress.
~release_lock:true releases the runtime lock during the call, so other threads can run. The arguments of the C function are C values that don't point into the OCaml heap, except for value types for which it is refused. The stub first runs the pending signal handlers and finalisers, which can raise, when it owns nothing yet; a signal arriving later is handled after the stub returns.
Helper
Camlid.Helper describes the common cases:
- the kind of parameters:
Camlid.Helper.input,Camlid.Helper.output,Camlid.Helper.inout,Camlid.Helper.ignored,Camlid.Helper.extra_input; - the scalars, e.g.
Camlid.Helper.int(intptr_t),Camlid.Helper.double,Camlid.Helper.bool, unboxed or untagged when possible; - strings and arrays, e.g.
Camlid.Helper.string_ntfor null terminated strings; - C values owned by OCaml:
Camlid.Helper.value_type,Camlid.Helper.custom_ptr,Camlid.Helper.custom,Camlid.Helper.abstract; - C enumerations and bit flags with
Camlid.Helper.enumandCamlid.Helper.flags,NULLasNonewithCamlid.Helper.nullable; - conversions to other C types with
Camlid.Helper.convert, and algebraic datatypes withCamlid.Helper.algdata.
When the C function takes the length of a string or an array as a separate argument, the helpers return two parameters, which are used in the same function:
(* void f(char *s, size_t len); *)
let f =
let a = string_len () in
func "f" [ a.t; a.len ]Only a.t is an argument of the OCaml function. Camlid.Helper.string_len_ref gives char ** and size_t * to the C function, and Camlid.Helper.fixed_length_string allocates the string with a length given as an OCaml argument.
Expert
Camlid.Expert defines new types and parameters. A type (Camlid.Ty.mlc) is a template: its OCaml type, C type, conversions, constructor and destructor are C code that mention its variables v (the OCaml value) and c (the C value). Camlid.Expert.param instantiates the template with fresh variables, and returns them so that they can be used in the other parameters of the function (e.g. the length of an array).
Each use of a type constructor creates new definitions. When printing, a C definition with the same basename and the same text as an already printed one is replaced by it, so a type can be built many times (e.g. ptr_ref int in each function) without duplicating code. Definitions with different names, like the stubs of two OCaml functions, are kept.
Camlid handles fresh identifiers with Camlid.Expr.id and variables with Camlid.Expr.var. A definition (a C function, a structure, an OCaml type) is attached to an identifier with Camlid.Expr.defined: printing the identifier adds the definition to the generated files, before its first use. Camlid.Expr.code defines a C function from its body; the variables used in the body become its formal parameters, unless they are in locals. Camlid.Expr.pp_call prints a call that applies each formal to an expression; the formals not applied are kept as variables, so they propagate to the calling context.