这可能吗?即用 dmc 编译 .c,用 dmd 编译 .d,然后将它们链接在一起,这行得通吗?我能否从 C 代码调用 D 函数、共享全局变量等?谢谢。
最佳答案
是的,这是可能的。事实上,这是 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.
}
}
// .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;
}
参见 Interfacing to C了解更多信息。
关于c - 在同一个程序中混合 C 和 D 代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3540596/