ocamllabs/ocaml-ctypes — pull request #27 by yallop (2013-06-27 16:30:57+00:00)
Title: Generic printing for C types and values

Generic printing for C types:

```OCaml
# array 3 char;;
- : char Ctypes.array Ctypes.typ = char[3]
# funptr (ptr int @-> returning (ptr (array 3 char)));;
- : (int Ctypes.ptr -> char Ctypes.array Ctypes.ptr) Ctypes.typ =
char(*(*)(int*))[3]
```

(The syntax follows standard C, so the [cdecl](http://cdecl.org/) program can unparse the result back into something like English:

```
cdecl> explain (char(*(*)(int*))[3])
cast unknown_name into pointer to function (pointer to int) returning pointer to array 3 of char
```
)

Generic printing for C values:

```OCaml
# type repr;;
type repr
# let repr = union "repr";;
val repr : '_a Ctypes.union Ctypes.typ = union repr
# let uint32 = repr +:+ uint32_t;;
val uint32 : (Unsigned.uint32, '_a Ctypes.union) Ctypes.field =
# let flt = repr +:+ float;;
val flt : (float, '_a Ctypes.union) Ctypes.field =
# let uchars = repr +:+ array (sizeof float) uchar;;
val uchars : (Unsigned.uchar Ctypes.array, '_a Ctypes.union) Ctypes.field =

# let () = seal (repr : repr union typ);;
# let r = make repr;;
val r : repr Ctypes.union = { 0 | 0.000000 | { 0, 0, 0, 0 } }
# setf r flt 3.14;;
- : unit = ()
# r;;
- : repr Ctypes.union = { 1078523331 | 3.140000 | { 195, 245, 72, 64 } }
```

(Compare
```OCaml
# Int32.bits_of_float 3.14;;
- : int32 = 1078523331l
```
)

There are new functions in the Ctypes module: `format` and `string_of` for printing values, `format_typ` and `string_of_typ` for printing object types, and `format_fn` and `string_of_fn` for printing function types. The new findlib package `ctypes.top` registers toplevel printers.