From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.1.3 (2006-06-01) on yquem.inria.fr X-Spam-Level: X-Spam-Status: No, score=0.0 required=5.0 tests=AWL autolearn=disabled version=3.1.3 X-Original-To: caml-list@yquem.inria.fr Delivered-To: caml-list@yquem.inria.fr Received: from concorde.inria.fr (concorde.inria.fr [192.93.2.39]) by yquem.inria.fr (Postfix) with ESMTP id BDBC3BC69 for ; Wed, 28 Mar 2007 13:47:12 +0200 (CEST) Received: from furbychan.cocan.org (furbychan.cocan.org [80.68.91.176]) by concorde.inria.fr (8.13.6/8.13.6) with ESMTP id l2SBlAWq021341 (version=TLSv1/SSLv3 cipher=EDH-RSA-DES-CBC3-SHA bits=168 verify=NO) for ; Wed, 28 Mar 2007 13:47:12 +0200 Received: from rich by furbychan.cocan.org with local (Exim 3.35 #1 (Debian)) id 1HWWcL-0002zW-00; Wed, 28 Mar 2007 12:47:05 +0100 Date: Wed, 28 Mar 2007 12:47:05 +0100 To: Joel Reymont Cc: Caml List Subject: Re: [Caml-list] Wrapping OCaml function returning a variant Message-ID: <20070328114704.GC1202@furbychan.cocan.org> References: Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: User-Agent: Mutt/1.5.9i From: Richard Jones X-Miltered: at concorde with ID 460A55BE.001 by Joe's j-chkmail (http://j-chkmail . ensmp . fr)! X-Spam: no; 0.00; ocaml:01 0100,:01 ocaml:01 val:01 pointer:01 pointer:01 val:01 reuse:01 28,:98 garbage:01 wrote:01 rewrite:01 caml-list:01 functions:01 strings:01 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