Mixing C and D code in the same program?

Is it possible? those. compile .c with dmc and .d with dmd and then link them together, will this work? Can I call D functions from C code, share global ones, etc.? Thanks.

+7
c d
source share
2 answers

Yes it is possible. In fact, this is one of the main features of dmd. To call function D from C, simply execute this function extern(C) , for example.

 // .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 Interaction with C for more details.

+10
source share

The above answer is incorrect as far as I know. Since before using any D-functions, you need to call the main procedure D. This is necessary to "initialize" D, i.e. his garbage collection. To solve this problem, you can simply enter the program into the main procedure in D or you can somehow call the main procedure D from C. (But I donโ€™t know exactly how it works)

+1
source share

All Articles