[ocaml-ctypes] Lifetime of Ctypes allocation
Markus Müller
llmarkvm at gmail.com
Mon Apr 18 23:02:31 BST 2016
Dear Jeremy,
thanks a lot for your elaborate reply. This program works as expected.
open Ctypes
open Foreign
let f = foreign "f" ((ptr (ptr int)) @-> returning void)
let v = ref (from_voidp (ptr int) null)
let a = ref (from_voidp int null)
let b = ref (from_voidp int null)
let _ =
v := allocate_n (ptr int) ~count:2 ;
a := allocate int 0 ;
b := allocate int 1 ;
(!v) <-@ (!a);
((!v) +@ 1) <-@ (!b) ;
f (!v) ; Gc.full_major () ; f (!v)
and the following program is fine too.
open Ctypes
open Foreign
let f = foreign "f" ((ptr (ptr int)) @-> returning void)
let v = allocate_n (ptr int) ~count:2
let a = allocate int 0
let b = allocate int 1
let _ =
v <-@ a;
(v +@ 1) <-@ b ;
f v ; Gc.full_major () ; f v
However, having v, a, b in a local scope does not work.
open Ctypes
open Foreign
let f = foreign "f" ((ptr (ptr int)) @-> returning void)
let _ =
let v = ref (from_voidp (ptr int) null) in
let a = ref (from_voidp int null) in
let b = ref (from_voidp int null) in
v := allocate_n (ptr int) ~count:2 ;
a := allocate int 0 ;
b := allocate int 1 ;
(!v) <-@ (!a);
((!v) +@ 1) <-@ (!b) ;
f (!v) ;
Gc.full_major () ;
f (!v)
I fail to see why it does not work in this case.
>> v <-@ (allocate int 0);
>
> This allocates an piece of C-memory large enough to hold an integer,
> initialized with 0. The address of the allocated memory is written to
> the C-memory referenced by 'v'.
>
> At this point there are no references to the original pointer returned
> by 'allocate', so the allocated memory may be freed.
Good point: (allocate int 0) is not bound to a variable and thus can be
freed. However, in the broken example above, a reference exists and
still it does not work. Can you explain why? Thank you.
Best regards,
Markus
More information about the Ctypes
mailing list