Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mixing C and D code in the same program?

Tags:

c

d

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.

like image 921
szx Avatar asked Aug 22 '10 07:08

szx


People also ask

Can I combine C and C++ at the same time?

The C++ language provides mechanisms for mixing code that is compiled by compatible C and C++ compilers in the same program. You can experience varying degrees of success as you port such code to different platforms and compilers.

How do I combine C and C++ codes?

Just declare the C++ function extern "C" (in your C++ code) and call it (from your C or C++ code). For example: // C++ code: extern "C" void f(int);

Does C and C++ use the same compiler?

Code structure of both the languages are same. The compilation of both the languages is similar. They share the same basic syntax. Nearly all of C's operators and keywords are also present in C++ and do the same thing.

Can I use C libraries in C++?

Yes - C++ can use C libraries. Except of course that you're using the C++ version of cstdio . To use the C one you need to #include <stdio. h> .


2 Answers

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.

like image 143
kennytm Avatar answered Oct 05 '22 21:10

kennytm


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)

like image 32
user449556 Avatar answered Oct 05 '22 20:10

user449556