[Issue 1648] Casting a function literal to void* swallows the function or segfaults

Derek Parnell derek at nomail.afraid.org
Thu Nov 8 15:48:15 PST 2007


On Thu, 8 Nov 2007 23:14:59 +0000 (UTC), d-bugmail at puremagic.com wrote:

> http://d.puremagic.com/issues/show_bug.cgi?id=1648
> 
> dhasenan at gmail.com changed:
> 
>            What    |Removed                     |Added
> ----------------------------------------------------------------------------
>              Status|NEW                         |RESOLVED
>          Resolution|                            |INVALID
> 
> ------- Comment #3 from dhasenan at gmail.com  2007-11-08 17:14 -------
> As Jarrett Billingsley pointed out, the error was in my code: taking the
> address of a local variable.

I made a slight change to the code and it seems to work. The 'send' member
function now receives the address of the delegate rather than the delegate
itself.

-------------
import std.stdio;

class Foo {
    private void* _funcptr;
    private void delegate()  _func;
    void send (void delegate ()* func) {
        _funcptr = cast(void*)func;
    }

    void sendTyped (void delegate () func) {
        _func = func;
    }

    void execute () {
        auto func = *cast(void delegate ()*) _funcptr;
        func();
    }

    void executeTyped () {
        _func();
    }
}

void main () {
    Foo foo = new Foo();
    // The following does nothing:
    auto func = { writefln("greetings"); };
    foo.send(&func);
    foo.execute();

    /* Uncommenting the following lines produces a segfault.
       Commenting the preceding lines and uncommenting the following
       produces the expected output. */
    foo.sendTyped({ writefln("this one is typed"); });
    foo.executeTyped();
}
-----------
-- 
Derek
(skype: derek.j.parnell)
Melbourne, Australia
9/11/2007 10:46:28 AM


More information about the Digitalmars-d-bugs mailing list