From : Jeremy Yallop <yallop AT gmail.com>

: Jeremy Yallop <yallop AT gmail.com> To : Caml List <caml-list AT inria.fr>

: Caml List <caml-list AT inria.fr> Subject : [Caml-list] ANN: ocaml-ctypes, a library for calling C functions directly from OCaml

: [Caml-list] ANN: ocaml-ctypes, a library for calling C functions directly from OCaml Date: Fri, 7 Jun 2013 00:17:47 +0100

I'm happy to announce the initial release of ocaml-ctypes.The ocaml-ctypes library makes it possible to call C functionsdirectly from OCaml without writing or generating C code. The core ofthe library is a set of combinators for describing C types -- scalars,functions, structs, unions, arrays, and pointers to values andfunctions. Type descriptions can then be used to bind nativefunctions and values. Here's a simple example:# let puts = foreign "puts" (string @-> returning int);;val puts : string -> int = # puts "Hello, world!";;Hello, world!Here's a more substantial example that shows how to describe a Cstructure type, map the type to an OCaml record, and call a functionthat returns the structure.(* Describe the C struct. There are two fields, both ints. *)let div_t = structure "div_t";;let q = div_t *:* intlet r = div_t *:* intlet () = seal div_t(* Define the OCaml record that we'll use to view the C structure. *)type div_result = { quot : int; rem: int }(* Define the conversions between the C struct and the OCaml record. *)let div_result_of_div_t d = { quot = getf d q; rem = getf d r }let div_t_of_div_result {quot; rem} =let d = make div_t in (setf d q quot; setf d r rem; d)(* Create a "view type" for that looks like div_result and behaveslike div_t *)let div_result = view ~read:div_result_of_div_t~write:div_t_of_div_result div_t(* Bind to the standard C `div' function *)let div = foreign "div" (int @-> int @-> returning div_result)(* Try it out *)# div 17 2;;- : div_result = {quot = 8; rem = 1}The distribution contains larger examples and a fairly extensive testsuite, showing how to use other features of the library, such asbinding to functions that accept callback arguments. Among theexamples is Anil Madhavapeddy's port of the `curses' example from theOCaml documentation; it's instructive to compare the twoimplementations:OCaml manual curses exampleocaml-ctypes curses exampleDetailed installation instructions for ocaml-ctypes can be found inthe tutorial. (Briefly: ensure libffi is installed, then 'opaminstall ctypes'.)Comments, bug reports, and other feedback are most welcome.Tutorial:Examples:API documentation: http://ocamllabs.github.io/ocaml-ctypes/ Github repository: https://github.com/ocamllabs/ocaml-ctypes Direct download: