【问题标题】:Calling a D function directly from C++直接从 C++ 调用 D 函数
【发布时间】:2014-11-14 06:08:58
【问题描述】:

我已经浏览了http://dlang.org/cpp_interface.html 并且在所有示例中,即使是某些 C++ 代码调用某些 D 代码的示例,主函数驻留在 D 中(因此被调用的二进制文件是从 D 源编译的那个)文件)。文档中的“从 C++ 调用 D”示例在 D 中定义了一个函数 foo,该函数从 C++ 中的函数 bar 中调用,而 bar 又从 D 中的主函数中调用。

是否可以只从 C++ 函数调用 D 代码?我正在尝试做一些简单的事情,如下所示,但不断收到构建错误:

在 D 中:

import std.stdio;

extern (C++) void CallFromCPlusPlusTest() {
  writeln("You can call me from C++");
}

然后在 C++ 中:

#include <iostream>

using namespace std;

void CallFromCPlusPlusTest();

int main() {
  cout << "hello world"<<"\n";
  CallFromCPlusPlusTest();
}

【问题讨论】:

    标签: c++ interop d


    【解决方案1】:

    是的,这是可能的,(您的里程可能会因使用的 C++ 编译器而异。)

    首先,您必须从 C++ 或 D 端初始化 D 运行时。

    cpptestd.d:

    import std.stdio;
    
    extern (C++) void CallFromCPlusPlusTest() {
      /*
       * Druntime could also be initialized from the D function:
      import core.runtime;
      Runtime.initialize();
      */
      writeln("You can call me from C++");
      //Runtime.terminate(); // and terminated
    }
    

    编译: dmd -c cpptestd.d

    cpptest.cpp:

    #include <iostream>
    
    using namespace std;
    
    void CallFromCPlusPlusTest();
    extern "C" int rt_init();
    extern "C" int rt_term();
    
    int main() {
      cout << "hello world"<<"\n";
      rt_init(); // initialize druntime from C++
      CallFromCPlusPlusTest();
      rt_term(); // terminate druntime from C++
      return 0;
    }
    

    编译和链接: g++ cpptest.cpp cpptestd.o -L/path/to/phobos/ -lphobos2 -pthread

    这适用于我在 Linux 上。

    【讨论】:

    • 你有可以显示字符串传递的例子吗?所以,你的 D 函数会收到一个字符串,最后加上“-response”,然后返回那个值?然后,C 中的 main 将 printf("RESULT=%s",CallFromCPlusPlusTest("request"); 并查看 RESULT=request-response。
    • 我拿了你的例子并大大扩展了它,以便它将一个字符串传递给 D,然后在最后用“-response”接收它。然后我解释了如何在 XCode 中加载这一切,以便它编译 D,然后甚至将它链接到一个 Objective C Cocoa 项目:forum.dlang.org/post/wihgbphoqytqqlxnefcb@forum.dlang.org
    猜你喜欢
    • 2011-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-04
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多