August 21, 2001 Member Function Pointers? | ||||
---|---|---|---|---|
| ||||
I didn't see any spec for member function pointers, so I thought I'd throw out an idea: You cannot take a pointer to a member function of a class; however, you can take a pointer to a member function of an *object*. The pointer returned contains both a pointer to the object and a pointer to the function, as found in the virtual function table. When you dereference the pointer, it automatically calls it as a member function. This means you won't have to write static wrappers for all of your callbacks. class Foo { int myFunc(int); }; int (Foo::myFuncPtr)(int); myFuncPtr = Foo.myFunc; // illegal Foo bar; myFuncPtr = bar.myFunc; // legal .... int baz = myFuncPtr(3); Also, I would hope that you could use member function pointers to interchange with C. My understanding is that in at least some C++ implementations, the this pointer is just passed as the first "invisible" argument; C could use this to call member functions. D would allow you to cast member function pointers to equivalent C structures. This means that you could have C code call member function callbacks: ***C API*** typedef int (*Callback)(void *,int); typedef struct { void *obj; Callback func; } CallbackPointer; ***D Code*** class Foo { extern C: int myCallback(int); }; Foo bar; CallbackPointer baz; baz = (CallbackPointer*)(bar.myCallback); // the D code then passes baz to the C code ***C Code*** /* time to call the callback */ CallbackPointer baz; int retCode = (baz.func)(baz.obj,3); |
Copyright © 1999-2021 by the D Language Foundation