Using delegates for C callbacks.

BCS ao at pathlink.com
Fri Feb 1 14:09:56 PST 2008


Reply to Leandro,

I have not tested this and don't have time to do so now

const auto sig = [ /* the binary form of nop; nop; nop; */ ];

R Thunker(T, A...)(A a)  // general thunk with tags
{
   T delegate(A) dg;
   dg.fn = 0xdeadbeef;
   dg.ptr = 0xabadf00d;
   return dg(a);
   asm {nop; nop; nop; nop; }
}


R function(A) Thuked(R, A...)(R delegate(A) dg)   // copy general thunk and 
replace tags with real stuff.
{
    byte* start = cast(byte*)(&R Thunker!(T, A));  // get thunk

    int stop = lengthTo(start, sig);  // find end

    start = start[0..stop].dup;  // copy

    stop = lengthTo(start, 0xdeadbeaf);  // relpace 
    (cast(void**)(start+stop))[0] = dg.fn;

    stop = lengthTo(start, 0xabadf00d);  // relpace
    (cast(void**)(start+stop))[0] = dg.ptr;

    return cast(typeof(ret)) start.ptr;   // return
}


note: the dg.ptr and dg.fn may be incorrect but IIRC there is a way to do 
that.




More information about the Digitalmars-d-learn mailing list