Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
Interfacing with C question...
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2007-01-25 (06:27)
From: Remi Vanicat <remi.vanicat@g...>
Subject: Re: [Caml-list] Interfacing with C question...
2007/1/24, David Allsopp <>:
> Sorry if this an RADBOTFM case. Rule 2 in Chapter 18 of the manual states
> that all local variables of type value must be declared using CAMLlocal
> macros. However, later on when demonstrating caml_callback we get the
> statements:
> value* format_result_closure = caml_named_value("format_result");
> return strdup(String_val(caml_callback(*format_result_closure, Val_int(n))))
> (I've "simplified" the opening lines for clarity here - naturally it should
> be static and once only!).
> Two questions arise:
> 1. Presumably it's OK to cache values returned by caml_named_value without
> declaring them in a CAMLlocal "call" or by using register_global_root?

No, any C pointer to a caml value must be known to the caml GC,
because the caml GC might move the caml value. But you might no
declare such a pointer if you are sur that the GC won't be triger
between your affectation of the value to the C variable, and the use
of the C variable.*

In the given exemple, this is the case: nothing is done between the
affectation and the use.

By the way, when in doubt, or when you are a begginer not nowing well
how the GC work, you should always use the CAMLlocal call.

> 2. The result of caml_callback is passed straight to String_val. Therefore,
> if I expand the line to:
> value result = caml_callback(*format_result_closure, Val_int(n)));
> return strdup(String_val(result));
> then does that work ok without using CAMLlocal1(result);

Yes, for the same reason: you do nothing between the affectation of
the result function, and the use of the variable.