Calling D functions from C

Matthias Walter Matthias.Walter at
Tue May 27 03:35:35 PDT 2008

Pontus Pihlgren Wrote:

> Hi all.
> Its a rather hypothetical I guess, but is it possible to call D 
> functions from C? If so, are there limitations?
> Kind Regards,
> Pontus.

If you want to really call the D function from C code, compiling with a C compiler, this can get tricky, as the C compiler normally does not know the ABI of D. It therefore does not know in which registers / stack slots to put which argument, etc.

But you can write a Wrapper routine in D which simply calls your D routine but has an extern (C) calling convention:

# extern (C) int myFunctionWrapper (char a, int b, char* c)
# {
#    return myFunction (a,b,c); // myFunction is a normal D function.
# }

With this code you can call myFunctionWrapper from your C code like you do normally. Alternatively you can code all your C stuff in a .d file, putting extern (C) around everything. Then you can call it without a wrapper, too.

best regards
Matthias Walter

More information about the Digitalmars-d-learn mailing list