Re: Q: How to call a CSL function from C

Xavier Leroy (xleroy@pauillac.inria.fr)
Fri, 15 Dec 1995 17:33:17 +0100 (MET)

From: Xavier Leroy <xleroy@pauillac.inria.fr>
Message-Id: <199512151633.RAA21304@pauillac.inria.fr>
Subject: Re: Q: How to call a CSL function from C
To: Leszek.Holenderski@gmd.de
Date: Fri, 15 Dec 1995 17:33:17 +0100 (MET)
In-Reply-To: <v01520d0bacf6f9220314@[129.26.12.124]> from "Leszek.Holenderski@gmd.de" at Dec 15, 95 01:40:00 pm

> I need to call some f: 'a -> 'b (in fact, 'a and 'b are some concrete
> types, but it doesn't matter here) from my C code linked with CSL 1.12. In
> my Caml code, I'll have the function
>
> external register_callback: ('a -> 'b) -> unit = "register_callback"
>
> such that 'register_callback f' will store, in my C code, enough
> information to call f later from the C code.

The correct way to do this is as follows (modified from your pseudocode):

static value f_closure = Val_int(0)

value register_callback (f);
value f;
{
register_global_root(&f_closure);
f_closure = f;
return Val_unit;
}

value invoke_f (arg)
value arg;
{
return callback(f_closure, arg);
}

The call to "register_global_root" ensures that the GC will not
deallocate the closure and will update the variable f_closure if the
closure gets moved. (This is documented in the user's manual.)

> The following code, borrowed from CamlTk for CL 0.7 (thus, from Francois
> Rouaix), seems to avoid the problem:

That was a terrible hack to work around the lack of a
"register_global_root" function in Caml Light 0.7. Forget about it.

- Xavier Leroy