tags:

views:

151

answers:

2

Is it possible? i.e. compile .c with dmc and .d with dmd and then link them together, will this work? Will I be able to call D functions from C code, share globals etc? Thanks.

+6  A: 

Yes it is possible. In fact this is one of the main feature of dmd. To call a D function from C, just make that function extern(C), e.g.

// .d
import std.c.stdio;
extern (C) {
  shared int x;    // Globals without 'shared' are thread-local in D2.
                   // You don't need shared in D1.
  void increaseX() {
    ++ x;
    printf("Called in D code\n");  // for some reason, writeln crashes on Mac OS X.
  }
}
// .c
#include <stdio.h>
extern int x;
void increaseX(void);

int main (void) {
  printf("x = %d (should be 0)\n", x);
  increaseX();
  printf("x = %d (should be 1)\n", x);
  return 0;
}

See Interfacing to C for more info.

KennyTM
+1 for the link to exactly the right page. Note that the C code and the D code must be in separate files. (Sounds obvious, but still should be stated explicitly.)
Donal Fellows
+1  A: 

The above answer is wrong as far as I know. Because the D main routine has to be called before you use any D functions. This is necessary to "initialize" D, f.e. its garbage collection. To solve that, you simply can make the program be entered by a main routine in D or you can somehow call the D main routine from C. (But I dont know exactly how this one works)

Here is a discussion from 2007 on that: http://www.digitalmars.com/d/archives/digitalmars/D/learn/Calling_D_from_C_-_What_s_the_present_status_6003.html
he_the_great