Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a C library from D?

Tags:

c

d

Today I heard about the D programming and that it is compatible to C code. Nevertheless I haven't found any information on whether it is possible to use C libraries like GTK or PortAudio from D? If it is possible, could you explain how to do this?

like image 872
ralle Avatar asked Oct 27 '09 12:10

ralle


2 Answers

It is possible to call C libraries from D. What you need to do is to convert the C header files to D. For the most part this is pretty straightforward, and there is a hard-to-use command-line tool to help automate the process. It's never really worked for me on anything but toy examples, but it could be a good start to see the kind of transformations that need to be done. Just put a snippet you're having trouble translating into a header by itself and see what htod does with it.

The biggest problem you'll usually encounter is creative use of the C preprocessor. Some things can be turned into version() statements in D, but not all.

As for actually compiling and linking with the code, on unix-like platforms I think you can compile and link in the C code using GCC. On Windows you either have to compile the C files using DMC and link with DMD. Or you can compile the C code into a DLL using any compiler capable of that, and then to link with DMD you need to make a DMD-compatible import lib out of the DLL. This can be done using the implib tool found in the free Basic Utilities Package available from DigitalMars.

There are also a lot of these header translations have already been done. It's useful to browse the Bindings project of Dsource first, or ask on the digitalmars D newsgroups first before embarking on something big like translating GTK headers. A lot of popular libraries like GTK have already been wrapped (e.g. here: GTKD)

like image 104
Baxissimo Avatar answered Oct 20 '22 07:10

Baxissimo


D code can be linked with C object files, and can interact with C dlls, but you'll need to generate a D module from the C header file you want to use. The official D website has a guide for doing that very thing.

like image 35
David Seiler Avatar answered Oct 20 '22 07:10

David Seiler