Stan
Stan

Reputation: 4239

Call C++(C) from D language

How do you call a C++ function from a D program? What commands should I use? I'm trying to use dmd on Fedora.

Upvotes: 11

Views: 3415

Answers (1)

Vlad
Vlad

Reputation: 18633

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.

Upvotes: 15

Related Questions