Call C++(C) from D language

无人久伴 提交于 2020-01-21 01:44:08

问题


How to call C++ function from D program? I still can't understand how to do it. What commands do I need to execute? I use dmd in Fedora.


回答1:


Simplest example I can think of, if you're calling C functions:

$ cat a.c
int f(int a, int b){
    return a + b + 42;
}
$ cat a.di
extern (C):
int f(int, int);
$ cat b.d
import std.stdio;
import a;
void main(){
    writeln( f( 100, 1000) );
}
$ gcc -c a.c
$ dmd b.d a.o
$ ./b
1142
$ 

If you're using shared objects, you could so something like:

$ cat sdltest.di
module sdltest;

extern (C):

struct SDL_version{
    ubyte major;
    ubyte minor;
    ubyte patch;
}

SDL_version * SDL_Linked_Version();

$ cat a.d
import std.stdio;
import sdltest;

void main(){
    SDL_version *ver = SDL_Linked_Version();
    writefln("%d.%d.%d", ver.major, ver.minor, ver.patch);
}

$ dmd a.d -L-lSDL
$ ./a
1.2.14
$ 

In this example, I linked with an SDL function. The -L argument to dmd allows you to pass arguments to ld, in this case -lSDL to link with SDL.

D interface files (.di) are described here.

You should also take a look at htod.



来源:https://stackoverflow.com/questions/10062750/call-cc-from-d-language

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