ocaml-ctypes icon indicating copy to clipboard operation
ocaml-ctypes copied to clipboard

String view and the GC

Open Drup opened this issue 11 years ago • 4 comments

In the top level :

# let s = "bla" ;;
val s : string = "bla"
# let s' = allocate string s ;;
val s' : string Ctypes.ptr = (char**) 0x29665f0
# !@s' ;;
- : string = "bla"
# Gc.full_major () ;;
- : unit = ()
# !@s'  ;;
- : string = "\160e\150\002""

According to the documentation, isn't the string view supposed to avoid this issue ?

Drup avatar Jun 25 '14 03:06 Drup

This is actually expected behaviour. The short summary as to why it occurs is that the string view copies values into C storage, which is reclaimed by the GC since your code doesn't retain any references to it.

In a little more detail, the second line is essentially equivalent to the following:

let p : char ptr = coerce string (ptr char) s
let q : char ptr ptr = allocate (ptr char) p
let s' : string ptr = coerce (ptr (ptr char)) (ptr string) q

except that no references are retained to the intermediate objects p and q. When the Gc runs it therefore reclaims p, which releases the associated C storage. You can prevent the premature reclamation happening by storing a reference to p in your program for as long as you want the associated C object to remain live.

yallop avatar Jul 04 '14 13:07 yallop

This is not consistent with the documentation : "To avoid problems with the garbage collector, values passed using Ctypes.string are copied into immovable C-managed storage before being passed to C.".

GC issues are not at all avoided :/

Currently, my workaround is to go through a CArray.

Drup avatar Jul 04 '14 16:07 Drup

Ok, let's make it clear in the documentation that the GC problem in question concerns movability/stability, not (e.g.) lifetime. How about "To avoid passing references to (movable) OCaml objects to C ..."?

yallop avatar Jul 04 '14 16:07 yallop

Ok, I understand the issue better, thanks for the explanation. I think the wording is better. Maybe It would deserve a small section in the FAQ about the fact that lifetime issues may arise (and the workaround you presented).

Drup avatar Jul 04 '14 17:07 Drup