forked from dlang/dlang.org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
interfaceToC.dd
365 lines (289 loc) · 10.3 KB
/
interfaceToC.dd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
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)
$(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 $(D __cdecl), $(D __far), $(D __stdcall),
$(LINK2
http://www.digitalmars.com/ctg/ctgLanguageImplementation.html#declspec,
$(D __declspec)),
or other such C
$(LINK2 http://www.digitalmars.com/ctg/ctgLanguageImplementation.html#extended, extended type modifiers)
in D. These are handled by
$(DPLLINK 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)
$(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 core.stdc.stdlib.malloc()
and core.stdc.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 core.stdc.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
$(DPLLINK phobos/core_memory.html#addRoot, std.gc.addRoot())
or
$(DPLLINK 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)
$(TABLE2 D And C Type Equivalence,
$(ELABORATE_HEADER)
$(TROW2 void, void)
$(TROW2 byte, signed char)
$(TROW2 ubyte, unsigned char)
$(TROW2 char, char, (chars are unsigned in D))
$(TROW2 wchar, wchar_t, (when $(D sizeof(wchar_t)) is 2))
$(TROW2 dchar, wchar_t, (when $(D sizeof(wchar_t)) is 4))
$(TROW2 short, short)
$(TROW2 ushort, unsigned short)
$(TROW2 int, int)
$(TROW2 uint, unsigned)
$(TROW3 ulong, unsigned long long, unsigned long)
$(TROW3 core.stdc.config.c_long, long, long)
$(TROW3 core.stdc.config.c_ulong, unsigned long, unsigned long)
$(TROW3PLUS long, long long, long, (or $(D long long)))
$(TROW3PLUS ulong, unsigned long long, unsigned long, (or $(D unsigned long long)))
$(TROW2 float, float)
$(TROW2 double, double)
$(TROW2 real, long double)
$(TROW2 cdouble, double _Complex)
$(TROW2 creal, long double _Complex)
$(TROW2 struct, struct)
$(TROW2 union, union)
$(TROW2 enum, enum)
$(TROW2 class, ,no equivalent)
$(TROW2 type *, type *)
$(TROW2 type[dim], type[dim])
$(TROW2 type[dim]*, type(*)[dim])
$(TROW2 type[], ,no equivalent)
$(TROW2 type1[type2], , no equivalent)
$(TROW2 type function(params), type(*)(params))
$(TROW2 type delegate(params), , no equivalent)
$(TROW2 size_t, size_t)
$(TROW2 ptrdiff_t, 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.
)
$(H2 Passing D Array Arguments to C Functions)
$(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,
$(THEAD D type, C type)
$(TROW $(I T)$(B *) , $(I T)$(B []))
$(TROW $(B ref) $(I T)$(B [)$(I dim)$(B ]) , $(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())
$(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)
$(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
$(HASH)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.
)
$(P D does not support declaring variables of anonymous struct types. In such a case you can define a named struct in D and make it private:)
$(CCODE
union Info // C code
{
struct
{
char *name;
} file;
};
)
---
union Info // D code
{
private struct File
{
char* name;
}
File file;
}
---
$(H2 Callbacks)
$(P D can easily call C callbacks (function pointers), and C can call
callbacks provided by D code if the callback is an $(D extern(C)) function,
or some other linkage that both sides have agreed to (e.g. $(D extern(Windows))).)
$(P Here's an example of C code providing a callback to D code:)
$(CCODE
void someFunc(void *arg) { printf("Called someFunc!\n"); } // C code
typedef void (*Callback)(void *);
extern "C" Callback getCallback(void)
{
return someFunc;
}
)
---
extern(C) alias Callback = int function(int, int); // D code
extern(C) Callback getCallback();
void main()
{
Callback cb = getCallback();
cb(); // invokes the callback
}
---
$(P And an example of D code providing a callback to C code:)
$(CCODE
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 = int function(int, int); // D code
extern(C) void printer(Callback callback);
extern(C) int sum(int x, int y) { return x + y; }
void main()
{
printer(&sum);
}
---
$(P For more info about callbacks read the $(LINK2 function.html#closures, closures) section.)
$(H2 $(LEGACY_LNAME2 Using C Libraries, using-c-libraries, Using Existing C Libraries))
$(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 $(LEGACY_LNAME2 C Globals, c-globals, Accessing C Globals))
$(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.
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;
---
)
Macros:
TROW2=$(TR2 $(TD $(D $1)), $(TD2 $(D $2) $(TAIL $+)))
TROW3=$(TR3 $(TD $(D $1)), $(TD $(D $2)), $(TD $(D $3)))
TROW3PLUS=$(TR3 $(TD $(D $1)), $(TD $(D $2)), $(TD $(D $3) $4))
TD2=$(MULTICOL_CELL 2, $0)
TITLE=Interfacing to C
WIKI=InterfaceToC