Object pointer from delegate

Don Clugston dac at nospam.com.au
Sun Aug 27 23:46:04 PDT 2006


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.

Yes, but it has been stated that it will change in DMD 2.0, when 
delegates and function pointers become the same. At which time it might 
not even be possible to get the object pointer from a delegate.

(Since the delegate will point to a thunk, it may be possible to 
disassemble the thunk to recover the object pointer. Maybe).



More information about the Digitalmars-d-learn mailing list