[ocaml-ctypes] Cheating on Foreign.foreign to use Unix.stat stubs

Jeremy Yallop yallop at gmail.com
Tue Oct 28 22:00:38 GMT 2014

On 27 October 2014 12:08, Andrea Giugliano <ag400 at leicester.ac.uk> wrote:
> I am using ctypes in order to passing null pointers as input of Unix
> syscalls.
> So far we used the Unix OCaml library to use syscalls (open, chdir, stat),
> but it does not allow passing null pointers as input paths of the syscalls
> (i.e. mkdir NULL is not possible using OCaml Unix.mkdir).
> The thing is I would like to avoid implementing again the logic of Unix
> operations after having create ctypes stubs,
> instead I was successful so far in using the Unix stubs as my C functions.
> For instance I can have:
> let my_mkdir = Foreign.foreign "unix_mkdir" ~checkerrno:true (string_opt @->
> returning int)

While this approach works to some extent, it's not recommended.  The
unix_mkdir function accepts and returns 'value' values, not strings
and ints:

   value unix_mkdir(value path, value perm)

Now, an OCaml string stored in a 'value' is represented similarly to a
C string -- i.e. as a pointer to the first byte of an array of char --
so some C functions that accept a 'value' will work as you expect when
you pass then a string using ctypes.  However, you're likely to run
into unexpected behaviour very quickly:

   # let string_length = Foreign.foreign "caml_string_length"  (string
@-> returning int);;
   val string_length : string -> int = <fun>
   # string_length "abc";;
   - : int = -1

There's good news, though: the Unix stubs in the standard library are
only thin wrappers around system calls, so you won't lose much by
binding to the system calls directly.  Further, David Sheets has
already written ctypes bindings to some of the functions you need; his
bindings don't currently accept null pointers, but you may be able to
adapt them to your needs:


More information about the Ctypes mailing list