Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all,

I need to wrap functions from a C API into D. As I have read in the DLang forums and the tutorial it should be sufficient to declare the C functions as extern (C). For the most part this works well as I am able to call the functions, which are imported as a lib.

Now I have one remaining problem. In the C API there are callbacks that I cannot connect to in D. The D wiki says that in the C code there should be a function called getCallback() which returns the void typedef of the callback. However, I only have the typedef declaration in C and no function that delivers the callback. When I try to assign the callback function in D I get compilation errors because I (obviously) cannot assign a function with no return value to a variable.

In Code it looks like this, where Events is a struct that has members like OnData declared as Callbacks:
C:
C
typedef void (*Callback)(void*);
void MyDtaCB(void* pVoid); // has no prototype in the API

Events.OnData = MyDtaCB;


D:
d
extern (C) alias HmsCEventCallback_t = int function(int, int);
extern (C) HmsCEventCallback_t MyDtaCB(void*);

// compilation error: should be called with (), but that does not work either since it returns void
Events.OnData = MyDtaCB; 


The callback alias declaration is straight from the D wiki. Still, in their example they have a function in C called getCallback() which is not available in my lib. It should look like this:

C
extern "C" Callback getCallback(void)
{
    return MyDtaCB;
}


I have now tried many ways to get this working. I think that the assignment of the callback in D would be as simple as in C but, as mentioned above, I get the compilation error.

So how can I get this done without having to modify the C API?

Any suggestions would be appreciated.
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900