Callbacks in D as void functions

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Nov 13 07:14:23 PST 2014


On 11/13/14 9:49 AM, Wsdes wrote:
> Hi all,
>
> I already posted this to Code Project, but maybe you have a
> solution for my problem.
>
> I am trying to write a wrapper for a C API in D. In C I have the
> following definition of a callback type:
>
> typedef void (*Callback)(void*);

in D, this would be:

alias Callback = void function(void *);

> In a struct all members are of the type Callback. In the main
> function each member is assigned a function like this:
>
> Events.OnData = MyDtaCB;
>
> Here the MyDtaCB function has no prototype but is defined as
> follows:
>
> void MyDtaCB(void* pVoid){
> // Do stuff
> }
>
> Now I tried to port this to D. The wiki says that callback
> functions should be declared as integer functions, so my D code
> looks like this:
>
> extern (C) alias CEventCallback_t = int function(int, int);
> extern (C) CEventCallback_t MyDtaCB(void*);

This doesn't look right. MyDtaCB is a function taking void *, that 
returns a function pointer.

Can you point at the wiki you are talking about?

> Here's the catch: when I try to assign the MyDtaCB function to a
> member of the Events struct, I get a compilation error because
> MyDtaCB is a void function and therefore returns no value. Seems
> to work in C, though, but I don't know how to handle this in D.

C is a lot looser in function pointer types.

Without more context of what you are doing, it's hard to diagnose this 
any further.

-Steve


More information about the Digitalmars-d-learn mailing list