Function to delegate conversion

Kirk McDonald kirklin.mcdonald at gmail.com
Sat Jun 24 23:27:13 PDT 2006


Some of the functionality of C++-style pointers to member functions is
lost with D's delegates. (In exchange for many advantages, don't get me 
wrong!)

For instance, I am currently looking at how to wrap D classes and
present them to Python. Parts of this look suprisingly easy. (Conversion
between the Python type and the D class, for instance, is going to be
much easier than I had previously feared.) But exposing a class's member
functions is tricky without C++-style pointers to member functions.
(Boost.Python utilizes them for this purpose.)

For instance:

class A {
     void foo() { }
}

void main() {
     A a = new A;
     void function() fn = &A.foo;
}

Without the ability to convert fn into a delegate to a.foo, implementing 
this class-wrapping functionality is all but impossible.

The way I'd do it if I had the ability to make this conversion is 
something not totally unlike this:

// T is the wrapped class
// Fn is the member function we're wrapping
template method_wrap(T, alias Fn) {
     extern(C)
     PyObject* func(PyObject* self, PyObject* args) {
         // Some concern needs to be had with respect to the GC, but
         // nevermind that.
         T t = *cast(T*)PyCObject_AsVoidPtr(self);
         // Something like this, only with a billion static ifs and more
         // template hooha.
         auto dg = delegate(t, &Fn); // Convert to a delegate
         dg();
         return something;
     }
}

-Kirk McDonald



More information about the Digitalmars-d mailing list