Calling function D directly from C ++

I went through http://dlang.org/cpp_interface.html and in all the examples, even those where some C ++ code calls some D code, the main function is in D (and therefore the binary code compiled from the source file is called D) The example of “calling D from C ++” in the doc document has a function foo defined in D that is called from the function bar in C ++, and bar, in turn, is called from the main function in D.

Is it possible to just call D code from a C ++ function? I am trying to do something simple as shown below, but keep creating 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();
}
+3
source share
1 answer

, ( ++.)

-, 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.

+7

Source: https://habr.com/ru/post/1619469/


All Articles