Browse thread
Wrapping OCaml function returning a variant
[
Home
]
[ Index:
by date
|
by threads
]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: | 2007-03-28 (11:47) |
From: | Richard Jones <rich@a...> |
Subject: | Re: [Caml-list] Wrapping OCaml function returning a variant |
On Wed, Mar 28, 2007 at 12:33:46PM +0100, Joel Reymont wrote: > The other issue is that I don't know how to deal with strings > allocated in OCaml. Will they be collected automatically? > > The strings _must_ be allocated in OCaml but I can guarantee that > they will not be modified in the C code. Any suggestions on how to > deal with this? String_val (ocaml_str) will give you a pointer to the bytes in the string. It's even ASCIIZ (ie. ASCII NUL-terminated) so you can directly use C str* functions on it. There are two catches: The small one is that OCaml strings may contain NUL characters internally, which is obviously not allowed in C strings, so you have to either guarantee on the OCaml side that this won't be the case, or else go through hoops on the C side. The bigger catch is that the garbage collector can and will move the string around whenever it likes. So if you save the pointer from String_val, go back into OCaml code and back into C, and try to reuse the saved pointer, it won't necessarily point to the string any more. The string might even have been freed by the GC. If you want to do that, either rewrite your code so it doesn't save the pointer like this, strdup the string to make a private copy in C, or register a global root. Rich. -- Richard Jones Red Hat