从C++直接调用D函数

4
我已经阅读了http://dlang.org/cpp_interface.html中的所有示例,即使是一些C++代码调用D代码的示例,主函数也是在D中(因此调用的二进制文件是从D源文件编译的)。文档中“从C ++调用D”的示例有一个在D中定义的函数foo,该函数从C ++中的函数bar中调用,而bar又从D中的主函数中调用。
直接从C++函数调用D代码是否可行?我正在尝试做一些简单的事情,如下所示,但始终出现构建错误:
在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();
}
1个回答

8

是的,这是可能的(取决于使用的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
}

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

使用以下命令进行编译和链接: g++ cpptest.cpp cpptestd.o -L/path/to/phobos/ -lphobos2 -pthread

这在Linux上对我有效。


你有一个可以展示传递字符串的例子吗?因此,你的D函数将接收一个字符串,在末尾添加“-response”,然后将该值返回?然后,C中的主要功能将printf("RESULT=%s",CallFromCPlusPlusTest("request");并查看RESULT=request-response。 - Volomike
我采用了你的示例,并大大扩展了它,以便将一个字符串传递给D,然后在末尾添加“-response”接收它。然后我解释了如何在XCode中加载所有内容,以便编译D甚至将其链接到Objective C Cocoa项目中:http://forum.dlang.org/post/wihgbphoqytqqlxnefcb@forum.dlang.org - Volomike

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接