Callbacks in D as void functions

Mike Parker via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Nov 13 17:34:54 PST 2014


On 11/14/2014 12:58 AM, Wsdes wrote:

> Anyway, I think I got the problem solved. Well, there seems to never
> have been any problem as I am taught now. I asked the developer of the C
> API this morning if I should try to implement the callback functions
> redundantly in D and he said he will have a look with me later. So now
> it turns out that I cannot call the extern callback function because
> it's not provided within the library O.O I was already wondering why
> there are no prototypes to these callback functions but I assumed they
> are provided from another library that I don't have direct access to...

Callbacks wouldn't be implemented in the library. They are intended to 
be implemented by the user of the library. That's why they're called 
"callbacks." The library "calls back" your function. In C, this is how 
event programming is usually handled. You pass a function pointer to the 
library and when some event occurs, the library calls your function (the 
callback).


>
> So the solution to my problem finally is to define the function in my D
> file and then cast the function pointer to the Callback type like this:
>
> void MyDtaCB(void* v){
>      // Do stuff
> }
>
> Events.OnData = cast(Callback) &MyDtaCB;
>

Define it as extern( C ) and you don't need the cast.

extern( C ) MyDtaCB( void* v ) { ... }
Events.OnData = &MyDtaCB;

Callbacks intended to be passed to C should *always* be implemented as 
extern( C ).





More information about the Digitalmars-d-learn mailing list