Calling C functions

Steven Schveighoffer schveiguy at gmail.com
Mon Jun 29 16:34:33 UTC 2020


On 6/26/20 4:15 AM, Jacob Carlborg wrote:
> On Friday, 26 June 2020 at 00:30:22 UTC, Denis wrote:
>> I have a two questions about calling C functions from D.
>>
>> (1) When passing a D callback to a C function, is there a way to write 
>> the code without having to prefix the callback declaration with 
>> "extern(C)"?
>>
>> It's not a big deal adding the prefix to the D function declaration. 
>> It just seems odd to me to prefix D code with "extern(C)". For 
>> example, the following code works:
>>
>>   extern(C) void cfunc(void function(int));
>>   extern(C) void dcallback(int x) {...}        <-- Why extern(C)?
>>   cfunc(&dcallback);
>>
>> Can this be rewritten, dropping the prefix from the second line? If 
>> not, it would be helpful to know why "extern(C)" is needed here too.
> 
> No, it cannot be dropped. `extern(C)` is required because C and D are 
> using different calling conventions (D functions are also mangled). For 
> example, D (at least DMD and LDC) are passing the arguments to the 
> function in reverse.

Are you sure? On the ABI page [1] , it says "The extern (C) and extern 
(D) calling convention matches the C calling convention used by the 
supported C compiler on the host system."

I'm pretty sure you can use function pointers to D functions for C 
callbacks, and it should work.

-Steve

[1] https://dlang.org/spec/abi.html#function_calling_conventions


More information about the Digitalmars-d-learn mailing list