On Tuesday, 27 May 2014 at 12:21:40 UTC, d coder wrote:
https://github.com/D-Programming-Language/dmd/pull/3181

Daniel asked me to use this. And it works.

Use something like:

union U
{
  void delegate(int) dg;
  struct
  {
    void* ptr;
    void function(int) funcptr;
  }
}
U u;
u.dg = dg;
u.funcptr = ...;
u.ptr = ...;

Regards
- Puneet

What's the current state of this? I'm in need of such behavior for win32 interop.

I'm thinking that one can make the above code more general by using it in a mixin and automatically generating the funcptr signature:


import std.stdio;
import std.concurrency;

extern (C) int getch();
import std.string;


template FancyDelegate(O, D)
{
const char[] FancyDelegate = "union "~O.stringof~"Delegate { "~D.stringof~" dg; struct { "~O.stringof~"* ptr; "~D.stringof.replace("delegate(", "function("~O.stringof~",").replace(",)", ")")~" funcptr; } }"; //const char[] FancyDelegate = "union "~O.stringof~"Delegate { "~D.stringof~" dg; struct { "~O.stringof~"* ptr; "~D.stringof.replace("delegate(", "function(")~" funcptr; } }";
}

class X
{
        public int z = 2;
        public void foo(int x)
        {
                //writeln(this.z*x);
                writeln(x);
        }
}

void delegate(int) dg;

mixin(FancyDelegate!(X, typeof(dg)));


void main()
{

        auto xX = new X();
        XDelegate x;
        x.dg = &xX.foo;
        
        //x.dg(3);
        x.ptr = &xX;
        x.funcptr(xX, 5);
        //x.funcptr(5);

        
        getch();
}

Unfortunately this fails when entering the function. I've tried various things(passing &xX, etc..., passing nothing(the comments, etc.)

I thought a delegate, when called, was called like a member function? It seems that a delegate is some magic black box that we can't emulate in any way shape or form due to the calling conventions used?

Reply via email to