Using delegates for C callbacks.

Leandro Lucarella llucax at gmail.com
Fri Feb 1 20:17:55 PST 2008


Leandro Lucarella, el  1 de febrero a las 22:09 me escribiste:
> Thanks, Kirk! The trick about passing the C.foo function instead of the
> c.foo method was defenely the trick. I adapted your example to what I
> needed, which is simpler because I don't need the Closure wrapper, so the
> code is more general without extra complexity:

Well, I had some problems with that code, and wasn't general enough. What
I really wanted was to be able to do something like this:


import std.stdio;

extern(C) void f(void function(void*) fn, void* closure) {
        fn(closure);
}

class C {
        int x;
        void foo() {
                writefln("C.foo: ", x);
        }
}

void thunk(void delegate() dg) {
        alias extern (C) void function(void*) fp;
        f(cast (fp) dg.funcptr, dg.ptr);
}

void main() {
        void foo() {
                writefln("foo");
        }
        C c = new C;
        c.x = 1;
        thunk(&c.foo);
        thunk(&foo);
}



This compiles... and *runs*! At least with GDC (DMD complains about "no
property 'funcptr' for type 'void delegate()'", I can see a lot of
problems with that code but that :S) on Linux.

Is this too wrong? I guess the casting from dg.funcptr to an extern (C)
function is not (I don't know if D calling convention is warrantied to be
the same as C, and I don't know if is warrantied that the first argument
to a delegate is the context pointer), but I really want the generality
and simplicity of this code, it makes no sense to need code more complex
than that to do what I want to do.

PS: Should I move this to digitalmars.D?

-- 
Leandro Lucarella (luca) | Blog colectivo: http://www.mazziblog.com.ar/blog/
----------------------------------------------------------------------------
GPG Key: 5F5A8D05 (F8CD F9A7 BF00 5431 4145  104C 949E BFB6 5F5A 8D05)
----------------------------------------------------------------------------
EXTRAÑA RELACION ENTRE UN JUBILADO Y UN JABALI
	-- Crónica TV


More information about the Digitalmars-d-learn mailing list