get Class from Pointer of member

Ali Çehreli acehreli at yahoo.com
Thu May 24 10:45:00 PDT 2012


On 05/24/2012 10:25 AM, StefanvT wrote:
> Hey thank you!! :-)
>
> I already tried to use offsetof on my own. But I always try to
> cast to a pointer.
> And this fails horribly :o)
>
> So thank you. I think I need to have a deeper look at references
> and pointer in D!
>
>

I should have mentioned that pointers to member functions are possible 
in D as delegates. A delegate keeps the object that it is bound to alive:

import std.stdio;

class C
{
     int i;

     void foo()
     {
         writeln("Called on object at ", &i);
     }
}

alias void delegate() MemberFunc;

MemberFunc return_object_delegate()
{
     auto c = new C;
     c.foo();

     auto d = &c.foo;    // c will be kept alive
     return d;
}

void main()
{
     auto d = return_object_delegate();
     // ... some time later
     d();
}

Ali

-- 
D Programming Language Tutorial: http://ddili.org/ders/d.en/index.html


More information about the Digitalmars-d-learn mailing list