[ocaml-ctypes] Converting from int to file_descr

David Sheets sheets at alum.mit.edu
Fri Jun 6 11:30:41 BST 2014

On Thu, Jun 5, 2014 at 8:20 PM, Costel Person <costel.person at gmail.com> wrote:
> I am trying to call forkpty
> pid_t forkpty(int *amaster, char *name, const struct termios *termp, const
> struct winsize *winp);
> Only care about file descriptor 'amaster' and result : pid_t
> All is good:
>   let forkpty = foreign "forkpty" (ptr int @-> ptr void @-> ptr void @-> ptr
> void @-> returning int)
>     let amaster : int ptr = allocate int -1 in
>     let pid = forkpty amaster null null null in
>     let pipefd = !@ amaster
> Do not understand how to convert the int representing file descriptor to
> Unix.file_descr
> Or use a view to pass a Unix.file_descr as an int to forkpty ?
> Any help appreciated ...

Hi Costel,

I use the fd-send-recv package in opam for this coercion. The function
to use is Fd_send_recv.int_of_fd. You can easily create a ctypes view
for Unix.file_descr with

Ctypes.view ~read:Fd_send_recv.fd_of_int ~write:Fd_send_recv.int_of_fd

Internally, file descriptors are just OCaml ints as you can see from
Because of this, you could also easily implement this coercion
yourself. I prefer to adopt the tiny fd-send-recv dependency and
abstract this dirty Obj.magic business.

Hope this helps,

David Sheets

More information about the Ctypes mailing list