[
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: | -- (:) |
| From: | Xavier Leroy <Xavier.Leroy@i...> |
| Subject: | Re: fancy GC question |
> When I allocate an integer array in OCaml, which is always boxed, both > the pointers to and the elements are obviously contiguous in memory. > One could exploit this in C-interfaces under the restriction that the > array is never changed by the OCaml-runtime, e.g.: > > int *ar = (int *) &Field(v_ar, 0); > > And then one can read/write directly into the integer array without > having to follow an indirection (an intermediate pointer) by treating > "ar" as a normal C array. > > But is this really always safe if only C writes to the array? It is safe if the C code does not perform any allocation in the Caml heap while it is using the "ar" pointer. An allocation can trigger a garbage collection, which can move the Caml block denoted by "v_ar"; after this, the "ar" pointer no longer points inside the block! (If "v_ar" is registered as a local root with the garbage collector, its value will be updated after the GC to reflect the new address of the block; however, the GC has no mechanism for updating derived pointers such as "ar" in your example.) But, yes, this is a safe trick to use in e.g. a tight loop that does not allocate in the Caml heap. > Can other effects mess up the > fact that the pointers map continuously on a contiguous chunk of memory > (of integers)? I'm not sure I understand the question, but the various "fields" of a Caml block (as accessed with the Field macro) are always contiguous in memory. - Xavier Leroy