On Sat, 16 Oct 2010 11:57:36 -0400, Steven Schveighoffer <schvei...@yahoo.com> wrote:

On Sat, 16 Oct 2010 11:22:43 -0400, Juanjo Alvarez <f...@fakeemail.com> wrote:

On Sat, 16 Oct 2010 14:42:13 +0000 (UTC), dsimcha <dsim...@yahoo.com> wrote:
delegate with minimal overhead.  This mitigates the situation a
lot, since if an
API requires a delegate and you have a function pointer, you just
do a
toDelegate(someFunctionPointer).

Sorry for asking here something that should go to D.learn, but how do you do the reverse, that is, getting a function from a delegate? I need that in my project so I can pass it to signal so some Unix signal will trigger a method of an already instantiated object.

auto dg = &obj.method;

auto fptr = dg.funcptr;
auto context = dg.ptr;

Note, you cannot call fptr, you will get a runtime error.

Here is the related documentation (search for funcptr): http://www.digitalmars.com/d/2.0/function.html

I believe there may be in phobos a type which wraps a function pointer into a delegate. Not sure if it was ever added though...

-Steve

Actually, you can use funcptr for simple functions. Here's an example how:

void main(string[] args) {
    auto foo = (int x){ writeln(x); };
    void function(int,void*) bar = foo.funcptr;
    bar(5,foo.ptr);
    foo(5);
    return;
}

Structs larger than 8 bytes require a hidden return pointer, so instead of

LargeStruct function(int,void*) bar;

you'd have

void function(int,LargeStruct*,void*) bar;

However, if Unix code needs to call the function, it needs to do so using the C calling conventions, which are platform/compiler specific.

Reply via email to