Callbacks in D as void functions

Wsdes via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Nov 13 07:58:32 PST 2014


On Thursday, 13 November 2014 at 15:17:45 UTC, Adam D. Ruppe 
wrote:
> On Thursday, 13 November 2014 at 14:50:00 UTC, Wsdes wrote:
>> 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*);
>
> I would translate this directly to D:
>
> extern(C) alias Callback = void function(void*);
>
>>
>> Here the MyDtaCB function has no prototype but is defined as
>> follows:
>>
>> void MyDtaCB(void* pVoid){
>> // Do stuff
>> }
>
> And don't forget extern(C) on this too:
>
> extern(C) void MyDtaCB(void* pVoid) {
>
> }
>
>
> And assign it to the struct:
>
> Events.OnData = &MyDtaCB;
>
>
>
> Unless you have a link to the wiki that talks about ints, maybe 
> that says something different, but I like to keep my C and D 
> code that calls it looking pretty much the same when I can.

Hi,

thank you everybody for your replies.

First of all, the link to the wiki that has an example of 
callbacks in C and D:
http://dlang.org/interfaceToC.html

Secondly, I tried your code and that was exactly what I was 
thinking and what I tried before. Then I thought I'd turn to the 
wiki example, so that's where the int function came from. In the 
meantime I changed that to return void so I gave you my old code 
:(

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...

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;

At least this one compiles. Now I'm facing other problems with 
struct members but I guess I'll figure this out. If not, I'll ask 
again so stay tuned for some more unsolved mysteries ;)

Still, thank you all for your effort and time. Keep it up! :)


More information about the Digitalmars-d-learn mailing list