ocaml-ctypes
ocaml-ctypes copied to clipboard
Tie the lifetime of OCaml strings and automatic C copies together?
[From a question by Andre Nathan on the mailing list]
When a function is bound like this:
let foo = foreign "foo" (string @-> returning void)
then passing an OCaml string to foo
automatically creates a C string whose lifetime is the duration of the call. In contrast, when a function is bound like this:
let bar = foreign "bar" (funptr (void @-> returning void) @-> returning void)
then passing an OCaml function f
to bar
automatically creates a C function pointer whose lifetime is no shorter than the lifetime of f
.
It might be possible, and would sometimes be useful, to extend the string
behaviour to be more like funptr
, so that the copies created when strings are passed to C live as long as the original OCaml strings. (One difficulty in the function pointers implementation arises with strings, too: it's not possible to attach finalizers to statically allocated strings.)
FYI, in a general context, it might be useful to consider C++ lifetime rules for temporaries as a guide, although it isn't clear how to implement this.
One way might be to allocate all temporaries in a pool, and explicit scope the pool like this:
pool_release (foo (bar (arg1 arg2, let xx = arg4 in .. arg8 ......))))
This would release all things considered "pool temporaries" inside an arbitrary Ocaml expression allowing a finite number to live through the whole body of a loop, but be released and reallocated each iteration.
@andrewray raised another question on the mailing list:
In the case where a C function takes and returns the same string, does a signature of [string @-> returning string] also work? In other words, does the input string live long enough to ensure the output string is created?
It would be good to ensure (and document) that this is guaranteed to work, and to check similarly that values associated with views are properly preserved across callbacks.