Calling a D function directly from C++

后端 未结 1 1724
情歌与酒
情歌与酒 2021-01-19 10:14

I\'ve gone through http://dlang.org/cpp_interface.html and in all of the examples, even those where some C++ code calls some D code, the main function resides in D (and so t

1条回答
  •  生来不讨喜
    2021-01-19 10:59

    Yes it is possible, (your mileage may vary depending on the C++ compiler used.)

    Firstly, you will have to initialized the D runtime, either from the C++ or the D side.

    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
    }
    

    Compile with: dmd -c cpptestd.d

    cpptest.cpp:

    #include 
    
    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;
    }
    

    Compile and link with: g++ cpptest.cpp cpptestd.o -L/path/to/phobos/ -lphobos2 -pthread

    This works for me on Linux.

    0 讨论(0)
提交回复
热议问题