Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call C++(C) from D language

Tags:

c++

c

d

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.

like image 361
Stan Avatar asked Apr 08 '12 12:04

Stan


People also ask

Is there a programming language called D?

D, also known as dlang, is a multi-paradigm system programming language created by Walter Bright at Digital Mars and released in 2001. Andrei Alexandrescu joined the design and development effort in 2007.

What is BetterC?

BetterC is a subset of D that relies only on the existence of the C Standard library.


1 Answers

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.

like image 182
Vlad Avatar answered Sep 23 '22 10:09

Vlad