在同一程序中混合使用C和D代码?

szx*_*szx 7 c d

可能吗?即使用dmc编译.c和使用dmd编译.d然后将它们链接在一起,这会有效吗?我能从C代码调用D函数,共享全局变量等吗?谢谢.

ken*_*ytm 10

对的,这是可能的.实际上这是dmd的主要特征之一.要从C调用D函数,只需创建该函数extern(C),例如

// .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.
  }
}
Run Code Online (Sandbox Code Playgroud)
// .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;
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅与C的接口.