Calling D functions from C
Pontus Pihlgren
pontus at update.uu.se
Tue May 27 04:18:54 PDT 2008
Matthias Walter skrev:
> 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
That sound almost to easy, I thought that extern could only refer to,
you know, external functions and not to declare new functions.
Looking more closely at the documentation at
http://www.digitalmars.com/d/2.0/interfaceToC.html verifies it :) I
guess I must have missed it the first time I read it.
Thanks,
Pontus.
More information about the Digitalmars-d-learn
mailing list