How to convert a member function pointer to a normal function pointer

Jarrett Billingsley kb3ctd2 at yahoo.com
Mon Apr 30 06:31:10 PDT 2007


"smithfox" <ssm.fox at gmail.com> wrote in message 
news:f12959$1ufe$1 at digitalmars.com...
> I think it is a classic problem when we try to write object-oriented codes 
> based on an unalterable C framework(such as window gui sdk);

I know a lot of Windows API callbacks allow you to pass a void* as a context 
pointer which is passed to your callback every time it's called back.  What 
you can do is create a shim function which is extern(Windows) and takes the 
void* context pointer, then creates a delegate which does the calling, like 
so:

class A
{
    void foo()
    {
        writefln("foo");
    }
}

extern(Windows) void callback(void* ctx)
{
    void delegate() dg;
    dg.funcptr = &A.foo;
    dg.ptr = ctx;
    dg();
}

void main()
{
    A a = new A();
    someCallbackAPIFunc(&callback, cast(void*)a);
}

This assumes that someCallbackAPIFunc takes the address of a callback 
function and a void pointer as the context.  Then, when your callback 
function is called, you just set up your delegate to use A.foo as the 
function and the context as the pointer (which is your instance of A), and 
then you call the delegate. 





More information about the Digitalmars-d mailing list