Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 36 ยท Tooling and Interop

Interoperating with C and C++ from D

Call C libraries from D and export D to C: extern(C) declarations, type mapping, strings and zero termination, callbacks, struct layout, importC and -betterC, with C-side demos.

D was designed to work with C: it can call any C function with no wrapper, share struct layouts and use C's calling convention. That makes the vast world of C libraries (SQLite, zlib, OpenGL, libc itself) available directly. This lesson covers declaring C functions, mapping types, passing strings and callbacks, and the other direction: exposing D to C.

D code is read-only on this site. The runnable C programs show the C side of each interface (the function being called, the layout and the callback convention) that a D declaration must match.

Declaring a C function

D
extern (C) int abs(int x);              // from libc
extern (C) double sqrt(double x);       // from libm
extern (C) int printf(const char* fmt, ...);

void main()
{
    printf("abs(-7) = %d\n", abs(-7));
}

extern (C) means "use the C calling convention and C name mangling" so the linker finds the C symbol. The standard bindings are already in the core.stdc packages: core.stdc.stdio, core.stdc.stdlib, core.stdc.string, core.stdc.math and more. You can also write extern (C): to apply it to a block. extern (C++) does the same for C++ functions, classes and namespaces: extern (C++, "ns").

Link libraries with dub ("libs": ["sqlite3"]) or the compiler's -L-lsqlite3.

Type mapping

C D
char, signed char, unsigned char char (UTF-8 code unit), byte, ubyte
short, int, long long short, int, long
long core.stdc.config.c_long (size varies by platform: 4 or 8 bytes)
size_t size_t
float, double float, double
T* T*
const char* const(char)*
void* void*
bool / _Bool bool (1 byte)
struct S struct S (same layout)

Never use D's long for C's long on a library that targets Windows and Linux: use c_long. D's int is always 32 bits and long always 64, unlike C.

Strings

C strings are zero-terminated; D strings are a pointer plus a length and are not necessarily zero-terminated (literals are, as a convenience). Convert with toStringz and fromStringz:

D
import std.string : toStringz, fromStringz;
import core.stdc.string : strlen;

extern (C) int puts(const(char)* s);

void main()
{
    puts("literal is fine".ptr);
    string name = "D language";
    puts(name.toStringz);                    // adds a terminating zero
    const(char)* cstr = getenv("HOME");
    string back = cstr.fromStringz.idup;     // copy into a D string
}

Two traps: a D string passed with .ptr may lack the terminator (use toStringz), and a pointer returned by C may be freed later, so idup a copy if you need to keep it.

Structs and layout

D structs have the same layout as C structs by default, so you can share them:

D
extern (C) struct Point { int x; int y; }
extern (C) void move(Point* p, int dx, int dy);

The C side defines move and D calls it with a pointer to its own Point. Use align(1) for packed structs, static assert(Point.sizeof == 8) to check, and __traits(offsetOf, ...) to compare field offsets. Here is the C side printing exactly those numbers:

C C side: the layout a D struct must match

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

A D struct Record { char tag; int value; double weight; } has the same offsets (0, 4, 8) and size (16) on the same platform, which is why static assert on sizes is a cheap safety net.

Callbacks

C libraries take function pointers. In D, pass a function marked extern (C) (a delegate with context cannot cross the boundary):

D
extern (C) int compareInts(const(void)* a, const(void)* b)
{
    return *cast(int*) a - *cast(int*) b;
}

import core.stdc.stdlib : qsort;

void main()
{
    int[] data = [5, 2, 9, 1];
    qsort(data.ptr, data.length, int.sizeof, &compareInts);
}

The usual C idiom for context is a void* user argument, which D code can fill with a pointer to a class or struct. The C side below shows qsort and a callback with user data, the contract D must honor:

C C side: qsort and a callback with context

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Exporting D to C

Make D functions callable from C with extern (C) and, in shared libraries, export:

D
extern (C) int add_ints(int a, int b) { return a + b; }

Link as a static or dynamic library, and C declares int add_ints(int, int);. Remember that the D runtime (and its GC) must be initialized: call rt_init() and rt_term() from core.runtime or use Runtime.initialize(), unless the library is built -betterC.

-betterC and importC

  • -betterC compiles a subset of D with no D runtime, no GC, no classes, exceptions or unittest runner: just structs, templates, CTFE and main as a C function. It is ideal for embedded targets and tiny libraries.
  • importC lets the D compiler (DMD 2.100+) import a .c file directly: import mylib; where mylib.c is a C source file, so you no longer write binding declarations by hand. C preprocessing is applied.
  • Tools: dstep converts C headers to D, and dpp lets you #include a C header in a D file.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does extern (C) on a function declaration do?

    It lets D call or define functions whose symbols and calling convention match C.
  2. 2. Which D type matches C's long portably?

    C's long varies in size by platform; D's long is always 64 bits.
  3. 3. Why use toStringz when passing a D string to C?

    D strings carry a length and may not be zero-terminated.
  4. 4. What does -betterC remove?

    It is a runtime-free subset; templates and CTFE still work.

Summary

  • extern (C) lets D call and expose C functions; core.stdc.* has the libc bindings.
  • Match types carefully (c_long, size_t) and check layouts with static assert.
  • Convert strings with toStringz and fromStringz; callbacks must be extern (C) functions.
  • -betterC, importC, dstep and dpp reduce binding work and runtime overhead.

Next: Project: A Tokenizer