Calling delegate in a dll callback fails silently

Adam D. Ruppe via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jun 16 20:35:42 PDT 2017


On Friday, 16 June 2017 at 22:17:07 UTC, Andre Pany wrote:
> int dgRef = cast(int) &(dg);

What is the type of dg there? This looks horribly, horribly wrong 
to me.

If it is type delegate, you took the address of a local variable, 
which is likely overwritten by the time the callback triggers. 
Moreover, even if you didn't get a pointer to local, a delegate 
is twice the size of a pointer and thus wouldn't fit in an int 
anyway...

If it is a direct function reference it might work, though then 
you might as well just use it directly as the callback.

> 	if (auto dg = *cast(NotifyEvent*)cast(void*) reference1)

This suggests you got a pointer to the pointer; an escaped 
reference to a local variable.

If the function is called immediately, the local is still in 
scope and valid, but if called later, the local goes away and 
gets overwritten, causing the dll thread to jump into nonsense 
and most likely crash and die.

What you want to use is a regular function with a global thing, 
an object reference kept alive, or a thunk.

Here's one fairly simple technique you can use:
https://stackoverflow.com/questions/22845175/pass-delegates-to-external-c-functions-in-d


More information about the Digitalmars-d-learn mailing list