Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

String view and the GC #159

Open
Drup opened this issue Jun 25, 2014 · 4 comments
Open

String view and the GC #159

Drup opened this issue Jun 25, 2014 · 4 comments

Comments

@Drup
Copy link

Drup commented Jun 25, 2014

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 ?

@yallop
Copy link
Owner

yallop commented Jul 4, 2014

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.

@Drup
Copy link
Author

Drup commented Jul 4, 2014

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.

@yallop
Copy link
Owner

yallop commented Jul 4, 2014

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 ..."?

@Drup
Copy link
Author

Drup commented Jul 4, 2014

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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants