Calling a D function directly from C++

一曲冷凌霜 提交于 2019-12-20 01:38:40

问题


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 the binary being called is the one compiled from the D source file). The "calling D from C++" example in the doc has a function foo defined in D, which gets called from a function bar in C++, and bar in turn gets called from the main function in D.

Is it possible to just call D code from the C++ function? I'm trying to do something simple like the following, but keep getting build errors:

In D:

import std.stdio;

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

Then in C++:

#include <iostream>

using namespace std;

void CallFromCPlusPlusTest();

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

回答1:


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

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

This works for me on Linux.



来源:https://stackoverflow.com/questions/26923976/calling-a-d-function-directly-from-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!