直接从C++调用D函数

Jus*_*tin 3 c++ interop d

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

是否可以从C++函数调用D代码?我正在尝试做类似以下的简单操作,但不断出现构建错误:

在D:

import std.stdio;

extern (C++) void CallFromCPlusPlusTest() {
  writeln("You can call me from C++");
}
Run Code Online (Sandbox Code Playgroud)

然后在C++中:

#include <iostream>

using namespace std;

void CallFromCPlusPlusTest();

int main() {
  cout << "hello world"<<"\n";
  CallFromCPlusPlusTest();
}
Run Code Online (Sandbox Code Playgroud)

小智 7

是的,这是可能的,(您的里程可能因使用的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
}
Run Code Online (Sandbox Code Playgroud)

编译: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;
}
Run Code Online (Sandbox Code Playgroud)

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

这适用于Linux.