[ocaml-ctypes] Lifetime of Ctypes allocation

Markus Müller llmarkvm at gmail.com
Sat Apr 16 13:44:37 BST 2016


Hello,

I'm having some trouble on how to properly control the lifetime of an
OCaml allocated Ctypes "data structure". Consider the following simple
C function.

#include <stdio.h>
void f(int * * p)
{
  printf("%d %d\n", *(p[0]), *(p[1]));
}

Using f in the way shown below is wrong since the memory pointed to by
the inner pointers is freed by Gc.full_major.

open Ctypes
open Foreign
let f = foreign "f" ((ptr (ptr int)) @-> returning void)
let _ =
  let v = allocate_n (ptr int) ~count:2 in
  let _ = v <-@ (allocate int 0); (v +@ 1) <-@ (allocate int 1) in
    f v ; Gc.full_major () ; f v

The following crude attempt to fix it does not work either even though
some references to the pointers are bound to global values.

open Ctypes
open Foreign
let f = foreign "f" ((ptr (ptr int)) @-> returning void)
let a = ref null
let b = ref null
let _ =
  let v = allocate_n (ptr int) ~count:2 in
  let _ = v <-@ (allocate int 0); (v +@ 1) <-@ (allocate int 1) ; a :=
(to_voidp (!@ v)) ; b := (to_voidp (!@ (v +@ 1))) in
    f v ; Gc.full_major () ; f v

How can the allocated memory be properly protected from being freed before time?
Thanks for your help.

Best regards,
Markus


More information about the Ctypes mailing list