delegates with C linkage

Mike Parker aldacron at
Fri Jun 4 17:45:47 PDT 2010

Zarathustra wrote:
> I have obtained a strange error message when I tried to use delegate as an
> argument in a C linkage function.
> private extern (C) static {
>   void d_foo_add_event_handler(Foo, void delegate());
> }
> class Foo {
>   void addEventHandler(void delegate() handler) {
>     d_foo_add_event_handler(this, handler);
>   }
> }
> //__________________________________________________________________________
> Error: function foo.d_foo_add_event_handler(Foo, void delegate()) does not
> match parameter types (Foo, void delegate())
> Error: cannot implicitly convert expression (handler) of type void delegate()
> to void delegate()
> The second error message is especially extreme.
> When I use:
>   struct DelegateVoid { void* ptr, funcptr; } // void delegate() ABI
>   ...
>   void d_foo_add_event_handler(Foo, DelegateVoid);
>   ...
>   d_foo_add_event_handler(this, *cast(DelegateVoid*)&handler);
> Everything works well but I still have no idea why I cannot implicitly use
> delegates.

For starters, your first delegate is declared in an extern(C) block, 
meaning it has C linkage. The second is declared outside of the block, 
meaning it has D linkage. So they are two different types of delegates.

Secondly, I'm not sure if you can pass delegates to a C function. C code 
wouldn't understand delegates. They are not the same as function 
pointers. I suggest you use function pointers instead, paying attention 
to linkage.

On an unrelated note, what are you expecting the static keyword to do in 
your function declaration? It does not restrict function visibility to 
module scope, as it does in C and C++. That's what private is for. Here, 
static is meaningless.

More information about the Digitalmars-d-learn mailing list