Difference between revisions of "D binding for C"

From D Wiki
Jump to: navigation, search
(Begin migrating from how-tos on dlang.org)
 
(Types)
Line 27: Line 27:
  
 
A little global search and replace will take care of renaming the C types to D types. The following table shows a typical mapping for 32 bit C code:
 
A little global search and replace will take care of renaming the C types to D types. The following table shows a typical mapping for 32 bit C code:
 +
 +
{| class="wikitable"
 +
|+Mapping C type to D type
 +
!C type
 +
!D type
 +
|-
 +
|long double
 +
|real
 +
|-
 +
|unsigned long long
 +
|ulong
 +
|-
 +
|long long
 +
|long
 +
|-
 +
|unsigned long
 +
|uint
 +
|-
 +
|long
 +
|int
 +
|-
 +
|unsigned
 +
|uint
 +
|-
 +
|unsigned short
 +
|ushort
 +
|-
 +
|signed char
 +
|byte
 +
|-
 +
|unsigned char
 +
|ubyte
 +
|-
 +
|wchar_t
 +
|wchar or dchar
 +
|-
 +
|bool
 +
|bool, byte, int
 +
|-
 +
|size_t
 +
|size_t
 +
|-
 +
|ptrdiff_t
 +
|ptrdiff_t
 +
 +
|}

Revision as of 04:06, 24 February 2014

While D cannot directly compile C source code, it can easily interface to C code, be linked with C object files, and call C functions in DLLs. The interface to C code is normally found in C .h files. So, the trick to connecting with C code is in converting C .h files to D modules. This turns out to be difficult to do mechanically since inevitably some human judgement must be applied. This is a guide to doing such conversions.

Preprocessor

.h files can sometimes be a bewildering morass of layers of macros, #include files, #ifdef's, etc. D doesn't include a text preprocessor like the C preprocessor, so the first step is to remove the need for it by taking the preprocessed output. For DMC (the Digital Mars C/C++ compiler), the command:

dmc -c program.h -e -l

will create a file program.lst which is the source file after all text preprocessing.

Remove all the #if, #ifdef, #include, etc. statements.

Linkage

Generally, surround the entire module with:

extern (C)
{
     /* ...file contents... */
}

to give it C linkage.

Types

A little global search and replace will take care of renaming the C types to D types. The following table shows a typical mapping for 32 bit C code:

Mapping C type to D type
C type D type
long double real
unsigned long long ulong
long long long
unsigned long uint
long int
unsigned uint
unsigned short ushort
signed char byte
unsigned char ubyte
wchar_t wchar or dchar
bool bool, byte, int
size_t size_t
ptrdiff_t ptrdiff_t