Version française
Home     About     Download     Resources     Contact us    
Browse thread
C Callback issues
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Alain Frisch <Alain.Frisch@i...>
Subject: Re: [Caml-list] C Callback issues
Thomas Fischbacher wrote:
> Hello all,
> 
> suppose I have a C library which provides functionality via registering C 
> callbacks that take a closure parameter. For the sake of this example,
> let's say via set_foo_callback(void (*f)(void *),void *closure_param).
> 
> Now, if I want to lift this to the OCaml level by writing a C 
> callback-wrapper which will use the closure arg to pass the OCaml 
> function to be called, I encounter a slight problem:
> 
> Callbacks have to be "announced globally" to C by means of 
> Callback.register. 

I guessed I missed something here. Why do you need to use Callback.register?

The problem I see is that you need to copy the pointer to the OCaml 
closure in a C data structure and register it as a global root. Now, if 
I understand correctly, you'd like to share a global root if the same 
function closure is used several times, and you want to implement this 
sharing efficiently.

1. If you think you'll never have more than a few hundreds closures, you 
can simply do a linear lookup.

2. You can also use the data code pointer as a hash key. It never 
changes, but especially in native code, this might not be a very good 
idea (because of the way curryfication and partial applications are 
treated). You can also hash (with something similar to polymorphic 
hashing) the content of the closure environment.

3. You can use directly the closure pointer as a hash key, but you must
update the hash table when the GC is triggered.

-- Alain