[ocaml-ctypes] proper way of wrapping syscalls concerning (check_)errno

Jeremy Yallop yallop at gmail.com
Fri Jul 17 14:35:25 BST 2015


On 17 July 2015 at 10:29, Jan Doms <jan.doms at gmail.com> wrote:
> How about just having an accessor (and maybe also a setter) for errno?
> If I'm not mistaken such operations can not currently be written with
> ctypes and need a bit of C, right?

Right.  It can *almost* be done solely in ctypes, like this:

   let errno = foreign_value "errno" int

except that the C standard leaves the exact definition of errno rather
unspecified.  For example, errno can be defined like this

   extern int errno;

or like this

   #define errno (*__internal_errno())

and the second one won't work with the above ctypes definition.
However, it's not difficult to write a couple of tiny wrappers to set
and retrieve errno:

   void set_errno(int e) { errno = e; }
   int get_errno(void) { return errno; }

together with ctypes bindings:

   let set_errno = foreign "set_errno" (int @-> returning void)
   let get_errno = foreign "get_errno" (void @-> returning int)

Some care might also be needed to ensure that nothing can change errno
between a call to a ctypes-bound function and the subsequent call to
get_errno.


More information about the Ctypes mailing list