Movatterモバイル変換


[0]ホーム

URL:


D Logo
Menu
Search

Language Reference

table of contents

Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page.Requires a signed-in GitHub account. This works well for small changes.If you'd like to make larger changes you may want to consider usinga local clone.

Interfacing to C

Contents
  1. Calling C Functions
  2. Storage Allocation
  3. Data Type Compatibility
  4. Passing D Array Arguments to C Functions
  5. Callingprintf()
  6. Structs and Unions
  7. Callbacks
  8. Using Existing C Libraries
  9. Accessing C Globals

D is designed to fit comfortably with a C compiler for the target system. It is able to call C functions directly without requiring wrapper functions.

This is done by matching the C compiler's data types, layouts, and function call/return sequences.

TheImportC compiler extension allows importing or compiling.c files directly.

Bindings for popular C libraries can be found in thestandard library andpackage repository.

The rest of this page describes the manual, low-level side of interfacing with C.

Calling C Functions

C functions can be called directly from D. There is no need for wrapper functions, argument swizzling, and the C functions do not need to be put into a separate DLL.

The C function must be declared and given a calling convention, most likely the "C" calling convention, for example:

extern (C)int strcmp(constchar* string1,constchar* string2);
and then it can be called within D code in the obvious way:
import std.string;int myDfunction(char[] s){return strcmp(std.string.toStringz(s),"foo");}

There are several things going on here:

C code can correspondingly call D functions, if the D functions use an attribute that is compatible with the C compiler, most likely the extern (C):

// myfunc() can be called from any C functionextern (C){void myfunc(int a,int b)    {        ...    }}

Storage Allocation

C code explicitly manages memory with calls tomalloc() andfree(). D allocates memory using the D garbage collector, so no explicit frees are necessary.

D can still explicitly allocate memory using core.stdc.stdlib.malloc() and core.stdc.stdlib.free(), these are useful for connecting to C functions that expect malloc'd buffers, etc.

If pointers to D garbage collector allocated memory are passed to C functions, it's critical to ensure that the memory will not be collected by the garbage collector before the C function is done with it. This is accomplished by:

An interior pointer to the allocated memory block is sufficient to let the GC know the object is in use; i.e. it is not necessary to maintain a pointer to the beginning of the allocated memory.

The garbage collector does not scan the stacks of threads not created by the D Thread interface. Nor does it scan the data segments of other DLLs, etc.

Data Type Compatibility

D And C Type Equivalence
DC
32 bit64 bit
voidvoid
bytesigned char
ubyteunsigned char
charchar (chars are unsigned in D)
wcharwchar_t (whensizeof(wchar_t) is 2)
dcharwchar_t (whensizeof(wchar_t) is 4)
shortshort
ushortunsigned short
intint
uintunsigned
core.stdc.config.c_longlonglong
core.stdc.config.c_ulongunsigned longunsigned long
core.stdc.stdint.intptr_tintptr_tintptr_t
core.stdc.stdint.uintptr_tuintptr_tuintptr_t
longlong longlong (orlong long)
ulongunsigned long longunsigned long (orunsigned long long)
floatfloat
doubledouble
reallong double
cdoubledouble _Complex
creallong double _Complex
structstruct
unionunion
enumenum
class no equivalent
type *type *
type[dim]type[dim]
type[dim], type()[dim]type[dim], type()[dim]
type[] no equivalent
type1[type2] no equivalent
type function(params)type(*)(params)
type delegate(params) no equivalent
size_tsize_t
ptrdiff_tptrdiff_t

These equivalents hold for most C compilers. The C standard does not pin down the sizes of the types, so some care is needed.

Passing D Array Arguments to C Functions

In C, arrays are passed to functions as pointers even if the function prototype says its an array. In D, static arrays are passed by value, not by reference. Thus, the function prototype must be adjusted to match what C expects.

D And C Function Prototype Equivalence
D typeC type
T*T[]
refT[dim]T[dim]

For example:

void foo(int a[3]) { ... } // C code
extern (C){void foo(refint[3] a);// D prototype}

Callingprintf()

printf can be directly called from D code:

import core.stdc.stdio;int main(){    printf("hello world\n");return 0;}

Printing values works as it does in C:

int apples;printf("there are %d apples\n", apples);

Correctly matching the format specifier to the D type is necessary. The D compiler recognizes the printf formats and diagnoses mismatches with the supplied arguments. The specification for the formats used by D is the C99 specification 7.19.6.1.

A generous interpretation of what is a match between the argument and format specifier is taken, for example, an unsigned type can be printed with a signed format specifier. Diagnosed incompatibilites are:

Strings

A string cannot be printed directly. But%.*s can be used:

string s ="betty";printf("hello %.*s\n",cast(int) s.length, s.ptr);

The cast toint is required.

size_t andptrdiff_t

These use thezu andtd format specifiers respectively:

import core.stdc.stdio : printf;int* p =newint, q =newint;printf("size of an int is %zu, pointer difference is %td\n",int.sizeof, p - q);

Non-Standard Format Specifiers

Non-Standard format specifiers will be rejected by the compiler. Since the checking is only done for formats as string literals, non-Standard ones can be used:

constchar* format ="value: %K\n";printf(format, value);

Modern Formatted Writing

An improved D function for formatted output isstd.stdio.writef().

Structs and Unions

D structs and unions are analogous to C's.

C code often adjusts the alignment and packing of struct members with a command line switch or with various implementation specific #pragmas. D supports explicit alignment attributes that correspond to the C compiler's rules. Check what alignment the C code is using, and explicitly set it for the D struct declaration.

D does not support bit fields. If needed, they can be emulated with shift and mask operations, or use thestd.bitmanip.bitfields library type.htod will convert bit fields to inline functions that do the right shift and masks.

D does not support declaring variables of anonymous struct types. In such a case, define a named struct in D and make it private:

union Info  // C code{    struct    {        char *name;    } file;};
union Info// D code{privatestruct File    {char* name;    }    File file;}

Callbacks

D can easily call C callbacks (function pointers), and C can call callbacks provided by D code if the callback is anextern(C) function, or some other linkage that both sides have agreed to (e.g.extern(Windows)).

Here's an example of C code providing a callback to D code:

void someFunc(void *arg) { printf("Called someFunc!\n"); }  // C codetypedef void (*Callback)(void *);extern "C" Callback getCallback(void){    return someFunc;}
extern(C)alias Callback =intfunction(int,int);// D codeextern(C) Callback getCallback();void main(){    Callback cb = getCallback();    cb();// invokes the callback}

And an example of D code providing a callback to C code:

extern "C" void printer(int (*callback)(int, int))  // C code{    printf("calling callback with 2 and 4 returns: %d\n", callback(2, 4));}
extern(C)alias Callback =intfunction(int,int);// D codeextern(C)void printer(Callback callback);extern(C)int sum(int x,int y) {return x + y; }void main(){    printer(&sum);}

For more info about callbacks read theclosures section.

Using Existing C Libraries

Since D can call C code directly, it can also call any C library functions, giving D access to the smorgasbord of existing C libraries. To do so, however, one needs to write a D interface (.di) file, which is a translation of the C .h header file for the C library into D.

For popular C libraries, the first place to look for the corresponding D interface file is theDeimos Project. If it isn't there already, please write and contribute one to the Deimos Project.

Accessing C Globals

C globals can be accessed directly from D. C globals have the C naming convention, and so must be in anextern (C) block. Use theextern storage class to indicate that the global is allocated in the C code, not the D code. C globals default to being in global, not thread local, storage. To reference global storage from D, use the__gshared storage class.

extern (C)extern__gsharedint x;
Embedded Documentation
Interfacing to C++
Copyright © 1999-2025 by theD Language Foundation | Page generated byDdoc on Fri Oct 10 22:16:58 2025

[8]ページ先頭

©2009-2025 Movatter.jp