Writing part of a C program in D
C and D can link together. This lets us use C functions in D and also lets us use D functions from C. Here, we'll integrate some of the code in D into a C project. This knowledge is also useful for writing callback functions in D while using a C library from the D code, and can be used for the JNI or P/Invoke code in Java and .NET as well. Thanks to extern(C)
, anything that can interface with C can also interface with D.
Getting ready
If you are using DMD on 32-bit Windows, you'll also want to get DMC for Windows—the Digital Mars C compiler. DMC is automatically installed by the D installer. If you are using DMD from the ZIP file distribution, you can get DMC as a ZIP file from http://digitalmars.com/.
How to do it…
Let's execute the following steps to write a part of a C program in D:
Before calling any D function from C, be sure to call
rt_init()
. You can declare this to beextern int rt_init();
. Don't forget to check the return value—it returns0
if initialization...