Anonymous Delegates

Russell Lewis webmaster at villagersonline.com
Mon Jun 16 22:02:53 PDT 2008


Jason House wrote:
>> As long as I'm asking about delegate stuff, something else I've been 
>> wondering too: I know this following syntax for calling a function isn't 
>> supported, but is there any technical reason preventing it from being 
>> possible?:
> 
> I believe converting from function to delegate is no problem, but the reverse is.  I believe functions exist for compatibility with C where just a function pointer is passed in.

We don't have implicit conversion of function pointers to delegates, 
though people have asked for it.  But it's an easy thing to do with an 
anonymous delegate:

BEGIN CODE
    void function(<args>) my_fp = <whatever>;
    void delegate(<args>) my_dg =
               delegate void(<args>) { my_fp(<args>); };
END CODE

You can't convert a delegate to a function pointer because a function 
pointer doesn't have any way to store a 'this' parameter.  However, if 
you need to call a delegate from C code, it's still possible; you simply 
have to allocate a delegate on the heap (with new), and save the 
delegate there; pass the pointer to that heap variable as a void* to the 
C code.  Then write an extern(C) wrapper which, given a void*, will turn 
it into a pointer-to-delegate and then call the delegate.



More information about the Digitalmars-d mailing list