pass a delegate to an API as a context pointer?

teo teo.ubuntu at yahoo.com
Tue Jul 3 03:46:27 PDT 2007


Jascha Wetzel Wrote:

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

Good point, however the "a" object is still alive. main() doesn't exit after calling b.test(&a.abc). There's more stuff bellow. So, the delegate is there and its address should still be valid.

Or maybe you mean that the delegate foo f in the context of void test(foo f) function and &a.abc isn't the same thing?

All I want right now is to understand what happen.




More information about the Digitalmars-d mailing list