pass a delegate to an API as a context pointer?

Jascha Wetzel firstname at mainia.de
Tue Jul 3 03:03:21 PDT 2007


teo wrote:
> teo Wrote:
> 
>> Russell Lewis Wrote:
>>> Your code below shouldn't work because void* is 4 bytes (a single 
>>> pointer) whereas a delegate is 8 bytes (two pointers).  But you can do this:
>> So, my only chance is if I wrap the delegate somehow. Thanks Russell.
> 
> By the way, I tried to pass the address of the delegate like this:
> 
> (for details see my first post in this thread)
> void test(foo f)
> {
> 	xyz(cast(callback)&handler, cast(void*)&f);
> }
> 
> Unfortunately I wasn't able to convert it back to delegate later in the callback:
> 
> static void handler(void *context)
> {
> 	foo f = *(cast(foo*)context);
> 	int i = f();	// call A.abc();
> }
> 
> It simply crashes. The context value is exactly the same as &f (in test). Any ideas why? Russell? Kirk?
> 

this is most likely because the pointer doesn't exist any more when the 
C library calls back. the &f from test() becomes invalid when test 
returns, because f goes out of scope.
you need to put the delegate in a place that lasts longer. if you don't 
have a function scope that lives long enough, put it on the heap and 
call std.gc.addRoot on it to make sure it's not collected by the GC.



More information about the Digitalmars-d mailing list