Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Cannot retrieve contributors at this time

481 lines (380 sloc) 10.63 kb
Ddoc
$(SPEC_S Interfacing to C,
$(P D is designed to fit comfortably with a C compiler for the target
system. D makes up for not having its own VM by relying on the
target environment's C runtime library. It would be senseless to
attempt to port to D or write D wrappers for the vast array of C APIs
available. How much easier it is to just call them directly.
)
$(P This is done by matching the C compiler's data types, layouts,
and function call/return sequences.
)
<h2>Calling C Functions</h2>
$(P 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.
)
$(P The C function must be declared and given a calling convention,
most likely the "C" calling convention, for example:
)
------
extern (C) int strcmp(char* string1, char* string2);
------
$(P 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");
}
------
$(P There are several things going on here:)
$(UL
$(LI D understands how C function names are "mangled" and the
correct C function call/return sequence.)
$(LI C functions cannot be overloaded with another C function
with the same name.)
$(LI There are no __cdecl, __far, __stdcall,
$(LINK2 http://www.digitalmars.com/ctg/ctgLanguageImplementation.html#declspec, __declspec),
or other such C
$(LINK2 http://www.digitalmars.com/ctg/ctgLanguageImplementation.html#extended, extended type modifiers)
in D. These are handled by
$(LINK2 $(WEBURL)attribute.html#linkage, linkage attributes),
such as $(D extern (C)).)
$(LI There is no volatile type modifier in D. To declare a C function that uses
volatile, just drop the keyword from the declaration.)
$(LI Strings are not 0 terminated in D. See "Data Type Compatibility"
for more information about this. However, string literals in D are
0 terminated.)
)
$(P 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 function
extern (C) {
void myfunc(int a, int b) {
...
}
}
------
<h2>Storage Allocation</h2>
$(P C code explicitly manages memory with calls to
$(LINK2 http://www.digitalmars.com/rtl/stdlib.html#malloc, malloc()) and
$(LINK2 http://www.digitalmars.com/rtl/stdlib.html#free, free()).
D allocates memory using the D garbage collector,
so no explicit free's are necessary.
)
$(P D can still explicitly allocate memory using std.c.stdlib.malloc()
and std.c.stdlib.free(), these are useful for connecting to C
functions that expect malloc'd buffers, etc.
)
$(P If pointers to D garbage collector allocated memory are passed to
C functions, it's critical to ensure that that memory will not
be collected by the garbage collector before the C function is
done with it. This is accomplished by:
)
$(UL
$(LI Making a copy of the data using std.c.stdlib.malloc() and passing
the copy instead.)
$(LI Leaving a pointer to it on the stack (as a parameter or
automatic variable), as the garbage collector will scan the stack.)
$(LI Leaving a pointer to it in the static data segment, as the
garbage collector will scan the static data segment.)
$(LI Registering the pointer with the garbage collector with the
$(V1 std.gc.addRoot())
$(V2 $(LINK2 $(WEBURL)phobos/core_memory.html#addRoot, std.gc.addRoot()))
or
$(V1 std.gc.addRange())
$(V2 $(LINK2 $(WEBURL)phobos/core_memory.html#addRange, std.gc.addRange()))
calls.)
)
$(P 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.
)
$(P 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 DLL's, etc.
)
<h2>Data Type Compatibility</h2>
$(TABLE2 D And C Type Equivalence,
$(TR <th rowspan=2>D</th><th colspan=2>C</th>)
$(TR $(TH 32 bit) $(TH 64 bit))
$(TR
$(TD $(B void))
$(TD2 $(B void))
)
$(TR
$(TD $(B byte))
$(TD2 $(B signed char))
)
$(TR
$(TD $(B ubyte))
$(TD2 $(B unsigned char))
)
$(TR
$(TD $(B char))
$(TD2 $(B char) (chars are unsigned in D))
)
$(TR
$(TD $(B wchar))
$(TD2 $(B wchar_t) (when sizeof(wchar_t) is 2))
)
$(TR
$(TD $(B dchar))
$(TD2 $(B wchar_t) (when sizeof(wchar_t) is 4))
)
$(TR
$(TD $(B short))
$(TD2 $(B short))
)
$(TR
$(TD $(B ushort))
$(TD2 $(B unsigned short))
)
$(TR
$(TD $(B int))
$(TD2 $(B int))
)
$(TR
$(TD $(B uint))
$(TD2 $(B unsigned))
)
$(V1
$(TR
$(TD $(B long))
$(TD $(B long long))
$(TD $(B long))
)
$(TR
$(TD $(B ulong))
$(TD $(B unsigned long long))
$(TD $(B unsigned long))
)
)
$(V2
$(TR
$(TD $(B c_long (in core.stdc.config)))
$(TD $(B long))
$(TD $(B long))
)
$(TR
$(TD $(B c_ulong (in core.stdc.config)))
$(TD $(B unsigned long))
$(TD $(B unsigned long))
)
$(TR
$(TD $(B long))
$(TD $(B long long))
$(TD $(B long (or long long)))
)
$(TR
$(TD $(B ulong))
$(TD $(B unsigned long long))
$(TD $(B unsigned long (or unsigned long long)))
)
)
$(TR
$(TD $(B float))
$(TD2 $(B float))
)
$(TR
$(TD $(B double))
$(TD2 $(B double))
)
$(TR
$(TD $(B real))
$(TD2 $(B long double))
)
$(V1
$(TR
$(TD $(B ifloat))
$(TD2 $(B float _Imaginary))
)
$(TR
$(TD $(B idouble))
$(TD2 $(B double _Imaginary))
)
$(TR
$(TD $(B ireal))
$(TD2 $(B long double _Imaginary))
)
$(TR
$(TD $(B cfloat))
$(TD2 $(B float _Complex))
)
$(TR
$(TD $(B cdouble))
$(TD2 $(B double _Complex))
)
$(TR
$(TD $(B creal))
$(TD2 $(B long double _Complex))
)
)
$(TR
$(TD $(B struct))
$(TD2 $(B struct))
)
$(TR
$(TD $(B union))
$(TD2 $(B union))
)
$(TR
$(TD $(B enum))
$(TD2 $(B enum))
)
$(TR
$(TD $(B class))
$(TD2 no equivalent)
)
$(TR
$(TD $(I type)$(B *))
$(TD2 $(I type) $(B *))
)
$(TR
$(TD $(I type)$(B [)$(I dim)$(B ]))
$(TD2 $(I type)$(B [)$(I dim)$(B ]))
)
$(TR
$(TD $(I type)$(B [)$(I dim)$(B ]*))
$(TD2 $(I type)$(B (*)[)$(I dim)$(B ]))
)
$(TR
$(TD $(I type)$(B []))
$(TD2 no equivalent)
)
$(TR
$(TD $(I type)$(B [)$(I type)$(B ]))
$(TD2 no equivalent)
)
$(TR
$(TD $(I type) $(B function)$(B $(LPAREN))$(I parameters)$(B $(RPAREN)))
$(TD2 $(I type)$(B (*))$(B $(LPAREN))$(I parameters)$(B $(RPAREN)))
)
$(TR
$(TD $(I type) $(B delegate)$(B $(LPAREN))$(I parameters)$(B $(RPAREN)))
$(TD2 no equivalent)
)
$(TR
$(TD $(B size_t))
$(TD2 $(B size_t))
)
$(TR
$(TD $(B ptrdiff_t))
$(TD2 $(B ptrdiff_t))
)
)
$(P These equivalents hold for most C compilers. The C standard
does not pin down the sizes of the types, so some care is needed.
)
$(V2
<h2>Passing D Array Arguments to C Functions</h2>
$(P 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.)
$(TABLE2 D And C Function Prototype Equivalence,
$(TR
$(TH D type)
$(TH C type)
)
$(TR
$(TD $(I T)$(B *))
$(TD $(I T)$(B []))
)
$(TR
$(TD $(B ref) $(I T)$(B [)$(I dim)$(B ]))
$(TD $(I T)$(B [)$(I dim)$(B ]))
)
)
$(P For example:)
$(CCODE
void foo(int a[3]) { ... } // C code
)
---
extern (C)
{
void foo(ref int[3] a); // D prototype
}
---
)
<h2>Calling printf()</h2>
$(P This mostly means checking that the
$(LINK2 http://www.digitalmars.com/rtl/stdio.html#printf, printf format specifier)
matches the corresponding D data type.
Although printf is designed to handle 0 terminated strings,
not D dynamic arrays of chars, it turns out that since D
dynamic arrays are a length followed by a pointer to the data,
the $(D %.*s) format works:
)
------
void foo(char[] string) {
printf("my string is: %.*s\n", string.length, string.ptr);
}
------
$(P The $(CODE printf) format string literal
in the example doesn't end with $(CODE '\0').
This is because string literals,
when they are not part of an initializer to a larger data structure,
have a $(CODE '\0') character helpfully stored after the end of them.
)
$(P An improved D function for formatted output is
$(CODE std.stdio.writef()).
)
<h2>Structs and Unions</h2>
$(P D structs and unions are analogous to C's.
)
$(P C code often adjusts the alignment and packing of struct members
with a command line switch or with various implementation specific
#pragma's. 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.
)
$(P D does not support bit fields. If needed, they can be emulated
with shift and mask operations,
or use the $(LINK2 phobos/std_bitmanip.html#bitfields, std.bitmanip.bitfields)
library type.
$(DPLLINK htod.html, htod) will convert bit fields to inline functions that
do the right shift and masks.
)
<h2>$(LNAME2 Using C Libraries, Using Existing C Libraries)</h2>
$(P 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.
)
$(P For popular C libraries, the first place to look for the corresponding
D interface file is the $(LINK2 https://github.com/D-Programming-Deimos/, Deimos Project).
If it isn't there already, and you write one, please contribute it
to the Deimos Project.
)
<h2>$(LNAME2 C Globals, Accessing C Globals)</h2>
$(P C globals can be accessed directly from D. C globals have the C naming
convention, and so must be in an $(D extern (C)) block.
Use the $(D extern) storage class to indicate that the global is allocated
in the C code, not the D code.
$(V2 C globals default to being in global, not thread local, storage.
To reference global storage
from D, use the $(D __gshared) storage class.)
)
---
extern (C) extern __gshared int x;
---
$(V1
<hr>
<h1>Interfacing to C++</h1>
$(P D does not provide an interface to C++, other than
through $(DPLLINK COM.html, COM programming). Since D, however,
interfaces directly to C, it can interface directly to
C++ code if it is declared as having C linkage.
)
$(P D class objects are incompatible with C++ class objects.
)
)
)
Macros:
TD2=<td colspan=2>$0</td>
TITLE=Interfacing to C
WIKI=InterfaceToC
Jump to Line
Something went wrong with that request. Please try again.