Calling C functions

Denis noreply at noserver.lan
Fri Jun 26 00:30:22 UTC 2020


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.

(2) Is there a way to restrict the invocation of a linked C 
function to one specific D function?

If the C header is defined in one of the core.stdc libraries, the 
import statement can either be global or inside a specific D 
function -- both work. In contrast, when the C function prototype 
is written directly into the D program (as above), the linker 
complains unless this declaration is made global. If it's 
possible to restrict the scope of the C function to just one D 
function, I'll take advantage.

(I'm using dmd, if that makes a difference.)

Thanks


More information about the Digitalmars-d-learn mailing list