Calling C functions

CrypticMetaphor CrypticMetaphor88 at gmail.com
Thu Dec 9 06:37:03 PST 2010


I found this page that describes how to call c functions from D.

I found this page that describes how:
http://arsdnet.net/dtips/#cfunc

on that page he uses gcc, and I use dmc, but I get different results. 
This is what I did

// cfile.c file
extern int globalFromD;

void functionFromC(int a) {
    globalFromD = a;
}
// end cfile.c

// dfile.d
extern(C) { // this is needed to make it available from C
         int globalFromD;
}
extern(C) { // also needed when listing the prototypes for your C functions
         void functionFromC(int);
}

import std.stdio; // for writefln

int main() {
         globalFromD = 100;
         writefln("%d", globalFromD);

         functionFromC(500);
         writefln("%d", globalFromD);

         return 0;
}
// end dfile.d

I compile with:
dmc -c cfile.c
And I get  an cfile.obj, which is the object code (.o in gcc).
Then I compile the D code
dmd dfile.d cfile.obj
and I get no errors, so I run it, the result:
// start result
C:\DCode\libtest>dfile.exe
100
100

C:\DCode\libtest>
// end result

Why is it still 100? It should be 500. I don't think functionFromC( int 
) is being called, and I can't really find any other sources that 
clearly explain how to do this simple stuff, so can anyone explain how 
to fix it?


More information about the Digitalmars-d-learn mailing list