【问题标题】:Mixing C and D code in the same program?在同一个程序中混合 C 和 D 代码?
【发布时间】:2010-08-22 07:39:51
【问题描述】:

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

【问题讨论】:

    标签: c d


    【解决方案1】:

    是的,这是可能的。事实上,这是 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 了解更多信息。

    【讨论】:

    • +1 链接到正确的页面。请注意,C 代码和 D 代码必须位于不同的文件中。 (听起来很明显,但仍应明确说明。)
    【解决方案2】:

    据我所知,上述答案是错误的。 因为在使用任何 D 函数之前必须调用 D 主例程。 这是“初始化” D, f.e. 所必需的。它的垃圾收集。 为了解决这个问题,你可以简单地让程序由 D 中的主例程进入,或者你可以以某种方式从 C 中调用 D 主例程。(但我不知道这个是如何工作的)

    【讨论】:

    猜你喜欢
    • 2012-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多