Object pointer from delegate

Lutger lutger.blijdestijn at gmail.com
Sat Aug 26 03:10:05 PDT 2006


Thanks! This can be useful if needed. Imho it would be nice if there was 
a delegate property to get the object pointer.

Kirk McDonald wrote:
> 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.
> 



More information about the Digitalmars-d-learn mailing list