Calling a D function from C
Michal Minich
michal.minich at gmail.com
Sat Nov 13 03:51:10 PST 2010
On Sat, 13 Nov 2010 00:00:00 +0100, Carlo wrote:
> On 12/11/2010 16:19, Michal Minich wrote:
>> V Fri, 12 Nov 2010 16:14:30 +0100, Carlo wrote:
>>
>>> Sorry if I bother you again with this probably silly problem. Here is
>>> the point. I want to call the D function "fun" from a .c file:
>>>
>>> \\file libforc.d
>>> extern (C) int fun(int x,int y){
>>> return x;
>>> }
>>> \\EOF
>>>
>>> \\file ctest.c
>>> #include<stdio.h>
>>>
>>> int fun(int,int);
>>>
>>> int main(int argc, char* argv[])
>>> {
>>> printf("%d",fun(2,3));
>>>
>>> return 0;
>>> }
>>> \\EOF
>>>
>>> This what I get trying to compile the .c file:
>>>
>>> $ dmd libforc.d -c
>>> $ gcc libforc.o ctest.c -m32
>>> libforc.o: In function `no symbol':
>>> libforc.d:(.text+0x8): undefined reference to `_Dmodule_ref' collect2:
>>> ld returned 1 exit status
>>>
>>> What did I miss?
>>
>> You probably need to include phobos library in gcc command line.
>
> Thanks for the reply. How do I do that? adding -lphobos doesn't work.
> Phobos sources seem to be in /src/phobos
Sorry, this was a bad advice.
first: extern (C) means that the function 'fun' is not defined in D, but
in C. So you can call it from D. like:
//file.d
extern (C) int fun(int x,int y);
void main () { writeln ( foo() ); }
//file.c
int fun(int x,int y){ return x; }
you can then compile C file in gcc to generate .o file, which can be used
with dmd.
But you want the opposite direction, which I'm not sure is possible, at
least in one executable. You should probably generate dynamic link
library in D and then use it in C.
there is how to do it in Windows, which doesn't help you much... :(
anyway, you should use word 'export' to make D functions accessible from
outside.
More information about the Digitalmars-d-learn
mailing list