Using delegates for C callbacks.
Leandro Lucarella
llucax at gmail.com
Fri Feb 1 13:34:55 PST 2008
Hi! I'm doing some code to interface with C and I need to use D delegates
as C callbacks.
I've tested a lot of posibilities to do this, asking on IRC channels, but
nothing seems to work entirely.
This is the closer I got:
1 import std.stdio;
2
3 extern (C) void f(void function(void*) cb, void* arg)
4 {
5 cb(arg);
6 }
7
8 extern (C) static void thunk(alias Fn)(void* arg)
9 {
10 Fn(arg);
11 }
12
13 void fcb(void* arg)
14 {
15 writefln("fcb: ", *cast (int*) arg);
16 }
17
18 class C
19 {
20 int x = 1;
21 void dcb(void* arg)
22 {
24 writefln("dcb: ", *cast (int*) arg, " = ", x);
25 }
26 }
27
28 void main()
29 {
30 int x = 1;
31 C c = new C;
32 thunk!(fcb)(&x);
33 //thunk!(c.dcb)(&x);
34 f(&thunk!(fcb), &x);
35 //f(&thunk!(c.dcb), &x);
36 }
The thunk for the plain function adaptation works fine, but not the
delegate. If I uncomment the code at line 33 I get:
thunk.d:10: Error: need 'this' to access member dcb
I have a void* pointer to use, I can "inject" the this pointer, but I
don't know how. Doing something like:
8 extern (C) static void thunk(alias Fn)(void* arg)
9 {
10 Fn.ptr = arg;
11 Fn();
12 }
Doesn't work, it says:
thunk.d:10: Error: no property 'ptr' for type 'void'
thunk.d:10: Error: constant dcb().ptr is not an lvalue
thunk.d:10: Error: cannot implicitly convert expression (arg) of type void* to int
Which I don't understand (specially the part of "no property 'ptr' for
type 'void'", why dcb is void? I don't think I understand very well the
semantics of an alias template parameter =S
Is there any recomended solution for this? I think it (or should be) a
fairly common problem (at least when making D bindings for C libraries).
--
Leandro Lucarella (luca) | Blog colectivo: http://www.mazziblog.com.ar/blog/
----------------------------------------------------------------------------
GPG Key: 5F5A8D05 (F8CD F9A7 BF00 5431 4145 104C 949E BFB6 5F5A 8D05)
----------------------------------------------------------------------------
FINALMENTE EL CABALLITO FABIAN VA A PASAR UNA BUENA NAVIDAD
-- Crónica TV
More information about the Digitalmars-d-learn
mailing list