c - 在同一个程序中混合 C 和 D 代码?

标签 c d

这可能吗?即用 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/

相关文章:

创建以太网 II 帧头?

为 Linux 创建一个窗口管理器

import - 多个文件中的相同模块名称

c - 从 C 中的输入动态读取字符串

c - sscanf 在 C 中带有 "_"分隔符

go - 哪种新语言最适合编写操作系统

list - D 自定义列表移除,垃圾收集器

dll - 用dmd编译D2语言时如何从DLL中导出变量?

reference - D 中的赋值操作会复制对象吗?

c - 如何在内核模块的相同偏移量中预留内存