Object pointer from delegate

Kirk McDonald kirklin.mcdonald at gmail.com
Fri Aug 25 17:24:27 PDT 2006


Lutger wrote:
> Is it possible to obtain the object pointer from a delegate that is 
> taken from a member function? Is it a hack?

Yes, it is a hack. Here's the method I use in Pyd:

struct FakeDG {
     Object instance;
     void* fn;
}

template dg_union(Dg) {
     union dg_union {
         FakeDG fake_dg;
         Dg real_dg;
     }
}

class Foo {
     void foo() { }
}

void main() {
     Foo f = new Foo;
     auto dg = &f.foo;

     dg_union!(typeof(dg)) u;
     u.real_dg = dg;

     Foo g = cast(Foo)u.fake_dg.instance;
     assert(f is g);
}

This relies on the particular way that DMD represents delegates 
internally, which is not (yet) a part of the spec. I don't really expect 
this to change any time soon, but it should still be considered a hack.

-- 
Kirk McDonald
Pyd: Wrapping Python with D
http://pyd.dsource.org



More information about the Digitalmars-d-learn mailing list