直接从C ++调用D函数 [英] Calling a D function directly from C++

查看:138
本文介绍了直接从C ++调用D函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

是否可以从C ++函数调用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:

在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 ++编译器而异。)

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

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

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

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

Compile with: dmd -c cpptestd.d

cpptest.cpp:

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

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

这在Linux上适用于我。

This works for me on Linux.

这篇关于直接从C ++调用D函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆