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
Re: Q: How to call a CSL function from C
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 1995-12-15 (17:52)
From: Xavier Leroy <xleroy@p...>
Subject: Re: Q: How to call a CSL function from C

> 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;
      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