-
-
Notifications
You must be signed in to change notification settings - Fork 379
/
Copy pathcpp_interface.dd
1234 lines (987 loc) · 26.2 KB
/
cpp_interface.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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Ddoc
$(SPEC_S Interfacing to C++,
$(HEADERNAV_TOC)
$(P This document specifies how to interface with C++ directly.)
$(P It is also possible to indirectly interface with C++ code, either
through a $(DDLINK spec/interfaceToC, Interfacing to C, C interface) or a
COM interface.)
$(H2 $(LNAME2 general_idea, The General Idea))
$(P Being 100% compatible with C++ means more or less adding
a fully functional C++ compiler front end to D.
Anecdotal evidence suggests that writing such is a minimum
of a 10 man-year project, essentially making a D compiler
with such capability unimplementable.
Other languages looking to hook up to C++ face the same
problem, and the solutions have been:
)
$(OL
$(LI Support the COM interface (but that only works for Windows).)
$(LI Laboriously construct a C wrapper around
the C++ code.)
$(LI Use an automated tool such as SWIG to construct a
C wrapper.)
$(LI Reimplement the C++ code in the other language.)
$(LI Give up.)
)
$(P D takes a pragmatic approach that assumes a couple
modest accommodations can solve a significant chunk of
the problem:
)
$(UL
$(LI matching C++ name mangling conventions)
$(LI matching C++ function calling conventions)
$(LI matching C++ virtual function table layout for single inheritance)
)
$(H2 $(LNAME2 platform-compiler-support, Platform-Compiler Support))
$(P When building on windows, you should preferrably link your D code to MSVC compiled binaries.
You can link to both gcc and clang compiled binaries on linux.
On macOS, you should preferrably link to clang compiled binaries.)
$(H2 $(LNAME2 global-functions, Global Functions))
$(P C++ global functions, including those in namespaces, can be declared
and called in D, or defined in D and called in C++.)
$(H3 $(LNAME2 calling_cpp_global_from_d, Calling C++ Global Functions from D))
$(P Given a C++ function in a C++ source file:)
$(CPPLISTING
#include $(LT)iostream$(GT)
using namespace std;
int foo(int i, int j, int k)
{
cout << "i = " << i << endl;
cout << "j = " << j << endl;
cout << "k = " << k << endl;
return 7;
}
)
$(P In the corresponding D code, $(CODE foo)
is declared as having C++ linkage and function calling conventions:
)
------
extern (C++) int foo(int i, int j, int k);
------
$(P and then it can be called within the D code:)
------
extern (C++) int foo(int i, int j, int k);
void main()
{
foo(1, 2, 3);
}
------
$(P Compiling the two files, the first with a C++ compiler,
the second with a D compiler, linking them together,
and then running it yields:)
$(CONSOLE
$(GT) g++ -c foo.cpp
$(GT) dmd bar.d foo.o -L-lstdc++ && ./bar
i = 1
j = 2
k = 3
)
$(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 Because modules are not part of C++, each function with C++ linkage
in the global namespace must be globally unique within the program.)
$(LI There are no $(D __cdecl), $(D __far), $(D __stdcall), $(D __declspec), or other
such nonstandard C++ extensions in D.)
$(LI There are no volatile type modifiers in D.)
$(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.)
)
$(H3 $(LNAME2 calling_global_d_functions_from_cpp, Calling Global D Functions From C++))
$(P To make a D function accessible from C++, give it
C++ linkage:)
---
import std.stdio;
extern (C++) int foo(int i, int j, int k)
{
writefln("i = %s", i);
writefln("j = %s", j);
writefln("k = %s", k);
return 1;
}
extern (C++) void bar();
void main()
{
bar();
}
---
$(P The C++ end looks like:)
$(CPPLISTING
int foo(int i, int j, int k);
void bar()
{
foo(6, 7, 8);
}
)
$(P Compiling, linking, and running produces the output:)
$(CONSOLE
$(GT) dmd -c foo.d
$(GT) g++ bar.cpp foo.o -lphobos2 -pthread -o bar && ./bar
i = 6
j = 7
k = 8
)
$(H2 $(LNAME2 cpp-namespaces, C++ Namespaces))
$(P C++ symbols that reside in namespaces can be
accessed from D. A $(LINK2 attribute.html#namespace, namespace)
can be added to the `extern (C++)`
$(LINK2 attribute.html#linkage, LinkageAttribute):
)
------
extern (C++, N) int foo(int i, int j, int k);
void main()
{
N.foo(1, 2, 3); // foo is in C++ namespace 'N'
}
------
$(P C++ can open the same namespace in the same file and multiple files.
In D, this can be done as follows:)
---
module ns;
extern (C++, `ns`)
{
int foo() { return 1; }
}
---
$(P Any expression that resolves to either a tuple of strings or an empty tuple is accepted.
When the expression resolves to an empty tuple, it is equivalent to `extern (C++)`)
---
extern(C++, (expression))
{
int bar() { return 2; }
}
---
$(P or in multiple files, by organizing them in a package consisting of several modules:)
---
ns/
|-- a.d
|-- b.d
|-- package.d
---
$(P File `ns/a.d`:)
---
module a; extern (C++, `ns`) { int foo() { return 1; } }
---
$(P File `ns/b.d`:)
---
module b; extern (C++, `ns`) { int bar() { return 2; } }
---
$(P File `ns/package.d`:)
---
module ns;
public import a, b;
---
$(P Then import the package containing the extern C++ declarations as follows:)
---
import ns;
static assert(foo() == 1 && bar() == 2);
---
$(P Note that the `extern (C++, `ns`)` linkage attribute affects only the ABI (name mangling and calling convention) of
these declarations. Importing them follows the usual
$(LINK2 spec/module, D module import semantics).)
$(P Alternatively, the non-string form can be used to introduce a scope. Note that the
enclosing module already provides a scope for the symbols declared in the namespace.
This form does not allow closing and reopening the same namespace with in the same module. That is:)
---
module a; extern (C++, ns1) { int foo() { return 1; } }
---
---
module b; extern (C++, ns1) { int bar() { return 2; } }
---
---
import a, b;
static assert(foo() == 1 && bar() == 2);
---
$(P works, but:)
---
extern (C++, ns1) { int foo() { return 1; } }
extern (C++, ns1) { int bar() { return 2; } }
---
$(P does not. Additionally, aliases can be used to avoid collision of symbols:)
---
module a; extern (C++, ns) { int foo() { return 1; } }
---
---
module b; extern (C++, ns) { int bar() { return 2; } }
---
---
module ns;
import a, b;
alias foo = a.ns.foo;
alias bar = b.ns.bar;
---
---
import ns;
static assert(foo() == 1 && bar() == 2);
---
$(H2 $(LNAME2 classes, Classes))
$(P C++ classes can be declared in D by using the $(CODE extern (C++))
attribute on $(CODE class), $(CODE struct) and $(CODE interface)
declarations. $(CODE extern (C++)) interfaces have the same restrictions as
D interfaces, which means that Multiple Inheritance is supported to the
extent that only one base class can have member fields.)
$(P $(CODE extern (C++)) structs do not support virtual functions but can
be used to map C++ value types.)
$(P Unlike classes and interfaces with D linkage, $(CODE extern (C++))
classes and interfaces are not rooted in $(CODE Object) and cannot be used
with $(CODE typeid).)
$(P D structs and classes have different semantics whereas C++ structs and
classes are basically the same. The use of a D struct or class depends on
the C++ implementation and not on the used C++ keyword.
When mapping a D $(CODE class) onto a C++ $(CODE struct),
use $(CODE extern(C++, struct)) to avoid linking problems with C++ compilers
(notably MSVC) that distinguish between C++'s $(CODE class) and $(CODE struct)
when mangling. Conversely, use $(CODE extern(C++, class)) to map a D
$(CODE struct) onto a C++ $(CODE class).)
$(P $(CODE extern(C++, class)) and $(CODE extern(C++, struct)) can be combined
with C++ namespaces:)
---
extern (C++, struct) extern (C++, foo)
class Bar
{
}
---
$(H3 $(LNAME2 using_cpp_classes_from_d, Using C++ Classes From D))
$(P The following example shows binding of a pure virtual function, its
implementation in a derived class, a non-virtual member function, and a
member field:)
$(CPPLISTING
#include $(LT)iostream$(GT)
using namespace std;
class Base
{
public:
virtual void print3i(int a, int b, int c) = 0;
};
class Derived : public Base
{
public:
int field;
Derived(int field) : field(field) {}
void print3i(int a, int b, int c)
{
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "c = " << c << endl;
}
int mul(int factor);
};
int Derived::mul(int factor)
{
return field * factor;
}
Derived *createInstance(int i)
{
return new Derived(i);
}
void deleteInstance(Derived *&d)
{
delete d;
d = 0;
}
)
$(P We can use it in D code like:)
---
extern(C++)
{
abstract class Base
{
void print3i(int a, int b, int c);
}
class Derived : Base
{
int field;
@disable this();
override void print3i(int a, int b, int c);
final int mul(int factor);
}
Derived createInstance(int i);
void deleteInstance(ref Derived d);
}
void main()
{
import std.stdio;
auto d1 = createInstance(5);
writeln(d1.field);
writeln(d1.mul(4));
Base b1 = d1;
b1.print3i(1, 2, 3);
deleteInstance(d1);
assert(d1 is null);
auto d2 = createInstance(42);
writeln(d2.field);
deleteInstance(d2);
assert(d2 is null);
}
---
$(P Compiling, linking, and running produces the output:)
$(CONSOLE
$(GT) g++ base.cpp
$(GT) dmd main.d base.o -L-lstdc++ && ./main
5
20
a = 1
b = 2
c = 3
42
)
$(P Note how in the above example, the constructor is not bindable and is
instead disabled on the D side; an alternative would be to reimplement the
constructor in D. See the $(DDSUBLINK spec/cpp_interface, lifetime-management,
section below on lifetime management) for more information.)
$(H3 $(LNAME2 using_d_classes_from_cpp, Using D Classes From C++))
$(P Given D code like:)
---
extern (C++) int callE(E);
extern (C++) interface E
{
int bar(int i, int j, int k);
}
class F : E
{
extern (C++) int bar(int i, int j, int k)
{
import std.stdio : writefln;
writefln("i = %s", i);
writefln("j = %s", j);
writefln("k = %s", k);
return 8;
}
}
void main()
{
F f = new F();
callE(f);
}
---
$(P The C++ code to access it looks like:)
$(CPPLISTING
class E
{
public:
virtual int bar(int i, int j, int k);
};
int callE(E *e)
{
return e->bar(11, 12, 13);
}
)
$(CONSOLE
$(GT) dmd -c base.d
$(GT) g++ klass.cpp base.o -lphobos2 -pthread -o klass && ./klass
i = 11
j = 12
k = 13
)
$(H2 $(LNAME2 structs, Structs))
$(P C++ allows a struct to inherit from a base struct. This is done in D using
`alias this`:)
---
struct Base { ... members ... };
struct Derived
{
Base base; // make it the first field
alias base this;
... members ...
}
---
$(P In both C++ and D, if a struct has zero fields, the struct still has a
size of 1 byte. But, in C++ if the struct with zero fields is used as a base
struct, its size is zero (called the
$(LINK2 https://en.cppreference.com/w/cpp/language/ebo, Empty Base Optimization)).
There are two methods for emulating this behavior in D.
The first forwards references to a function returning a faked reference to the base:)
---
struct Base { ... members ... };
struct DerivedStruct
{
static if (Base.tupleof.length > 0)
Base base;
else
ref inout(Base) base() inout
{
return *cast(inout(Base)*)&this;
}
alias base this;
... members ...
}
---
$(P The second makes use of template mixins:)
---
mixin template BaseMembers()
{
void memberFunction() { ... }
}
struct Base
{
mixin BaseMembers!();
}
struct Derived
{
mixin BaseMembers!();
... members ...
}
---
$(P Note that the template mixin is evaluated in the context of its
instantiation, not declaration. If this is a problem, the template mixin
can use local imports, or have the member functions forward to the
actual functions.)
$(H2 $(LNAME2 cpp-templates, C++ Templates))
$(P C++ function and type templates can be bound by using the
$(CODE extern (C++)) attribute on a function or type template declaration.)
$(P Note that all instantiations used in D code must be provided by linking
to C++ object code or shared libraries containing the instantiations.)
$(P For example:)
$(CPPLISTING
#include $(LT)iostream$(GT)
template$(LT)class T$(GT)
struct Foo
{
private:
T field;
public:
Foo(T t) : field(t) {}
T get();
void set(T t);
};
template$(LT)class T$(GT)
T Foo$(LT)T$(GT)::get()
{
return field;
}
template$(LT)class T$(GT)
void Foo$(LT)T$(GT)::set(T t)
{
field = t;
}
Foo$(LT)int$(GT) makeIntFoo(int i)
{
return Foo$(LT)int$(GT)(i);
}
Foo$(LT)char$(GT) makeCharFoo(char c)
{
return Foo$(LT)char$(GT)(c);
}
template$(LT)class T$(GT)
void increment(Foo$(LT)T$(GT) &foo)
{
foo.set(foo.get() + 1);
}
template$(LT)class T$(GT)
void printThreeNext(Foo$(LT)T$(GT) foo)
{
for(size_t i = 0; i $(LT) 3; ++i)
{
std::cout $(LT)$(LT) foo.get() $(LT)$(LT) std::endl;
increment(foo);
}
}
// The following two functions ensure that the required instantiations of
// printThreeNext are provided by this code module
void printThreeNexti(Foo$(LT)int$(GT) foo)
{
printThreeNext(foo);
}
void printThreeNextc(Foo$(LT)char$(GT) foo)
{
printThreeNext(foo);
}
)
---
extern(C++):
struct Foo(T)
{
private:
T field;
public:
@disable this();
T get();
void set(T t);
}
Foo!int makeIntFoo(int i);
Foo!char makeCharFoo(char c);
void increment(T)(ref Foo!T foo);
void printThreeNext(T)(Foo!T foo);
extern(D) void main()
{
auto i = makeIntFoo(42);
assert(i.get() == 42);
i.set(1);
increment(i);
assert(i.get() == 2);
auto c = makeCharFoo('a');
increment(c);
assert(c.get() == 'b');
c.set('A');
printThreeNext(c);
}
---
$(P Compiling, linking, and running produces the output:)
$(CONSOLE
$(GT) g++ -c template.cpp
$(GT) dmd main.d template.o -L-lstdc++ && ./main
A
B
C
)
$(H2 $(LNAME2 function-overloading, Function Overloading))
$(P C++ and D follow different rules for function overloading.
D source code, even when calling $(CODE extern (C++)) functions,
will still follow D overloading rules.
)
$(H2 $(LNAME2 memory-allocation, Memory Allocation))
$(P C++ code explicitly manages memory with calls to
$(CODE ::operator new()) and $(CODE ::operator delete()).
D's $(CODE new) operator allocates memory using the D garbage collector,
so no explicit delete is necessary. D's $(CODE new) operator is not
compatible with C++'s $(CODE ::operator new) and $(CODE::operator delete).
Attempting to allocate memory with D's $(CODE new) and deallocate with
C++ $(CODE ::operator delete) will result in miserable failure.
)
$(P D can explicitly manage memory using a variety of library tools, such as
with $(MREF std, experimental, allocator). Additionally,
$(CODE core.stdc.stdlib.malloc) and $(CODE core.stdc.stdlib.free) can be
used directly for connecting to C++ functions that expect $(CODE malloc)'d
buffers.
)
$(P If pointers to memory allocated on the D garbage collector heap are
passed to C++ functions, it's critical to ensure that the referenced memory
will not be collected by the D garbage collector before the C++ function is
done with it. This is accomplished by:
)
$(UL
$(LI Making a copy of the data using
$(MREF std, experimental, allocator) or $(CODE 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 using the
$(CODE core.memory.GC.addRoot) or $(CODE core.memory.GC.addRange)
functions.)
)
$(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 $(I beginning) of the allocated memory.
)
$(P The garbage collector does not scan the stacks of threads not
registered with the D runtime, nor does it scan the data segments of
shared libraries that aren't registered with the D runtime.
)
$(H2 $(LNAME2 data-type-compatibility, Data Type Compatibility))
$(TABLE2 D And C++ Type Equivalence,
$(THEAD D type, C++ type)
$(TROW
$(ARGS $(B void)),
$(ARGS $(B void))
)
$(TROW
$(ARGS $(B byte)),
$(ARGS $(B signed char))
)
$(TROW
$(ARGS $(B ubyte)),
$(ARGS $(B unsigned char))
)
$(TROW
$(ARGS $(B char)),
$(ARGS $(B char) (chars are unsigned in D))
)
$(TROW
$(ARGS $(D core.stdc.stddef.wchar_t)),
$(ARGS $(D wchar_t))
)
$(TROW
$(ARGS $(B short)),
$(ARGS $(B short))
)
$(TROW
$(ARGS $(B ushort)),
$(ARGS $(B unsigned short))
)
$(TROW
$(ARGS $(B int)),
$(ARGS $(B int))
)
$(TROW
$(ARGS $(B uint)),
$(ARGS $(B unsigned))
)
$(TROW
$(ARGS $(B long)),
$(ARGS $(B long) if it is 64 bits wide, otherwise $(B long long))
)
$(TROW
$(ARGS $(B ulong)),
$(ARGS $(B unsigned long) if it is 64 bits wide, otherwise $(B unsigned long long))
)
$(TROW
$(ARGS $(D core.stdc.config.cpp_long)),
$(ARGS $(B long))
)
$(TROW
$(ARGS $(D core.stdc.config.cpp_ulong)),
$(ARGS $(B unsigned long))
)
$(TROW
$(ARGS $(B float)),
$(ARGS $(B float))
)
$(TROW
$(ARGS $(B double)),
$(ARGS $(B double))
)
$(TROW
$(ARGS $(B real)),
$(ARGS $(B long double))
)
$(TROW
$(ARGS $(CODE extern (C++)) $(B struct)),
$(ARGS $(B struct) or $(B class))
)
$(TROW
$(ARGS $(CODE extern (C++)) $(B class)),
$(ARGS $(B struct) or $(B class))
)
$(TROW
$(ARGS $(CODE extern (C++)) $(B interface)),
$(ARGS $(B struct) or $(B class) with no member fields)
)
$(TROW
$(ARGS $(B union)),
$(ARGS $(B union))
)
$(TROW
$(ARGS $(B enum)),
$(ARGS $(B enum))
)
$(TROW
$(ARGS $(I type)$(B *)),
$(ARGS $(I type) $(B *))
)
$(TROW
$(ARGS $(B ref) $(I type) (in parameter lists only)),
$(ARGS $(I type) $(CODE_AMP))
)
$(TROW
$(ARGS $(I type)$(B [)$(I dim)$(B ])),
$(ARGS $(I type)$(B [)$(I dim)$(B ]) for a variable/field declaration,
or $(DDSUBLINK spec/interfaceToC, passing_d_array, use `ref` for function parameter))
)
$(TROW
$(ARGS $(I type)$(B [)$(I dim)$(B ]*)),
$(ARGS $(I type)$(B (*)[)$(I dim)$(B ]))
)
$(TROW
$(ARGS $(I type)$(B [])),
$(ARGS no `extern (C++)` equivalent, $(RELATIVE_LINK2 dynamic-arrays, see below))
)
$(TROW
$(ARGS $(I type)$(B [)$(I type)$(B ])),
$(ARGS no equivalent)
)
$(TROW
$(ARGS $(I type) $(B function)$(B $(LPAREN))$(I parameters)$(B $(RPAREN))),
$(ARGS $(I type)$(B (*))$(B $(LPAREN))$(I parameters)$(B $(RPAREN)))
)
$(TROW
$(ARGS $(I type) $(B delegate)$(B $(LPAREN))$(I parameters)$(B $(RPAREN))),
$(ARGS no equivalent)
)
)
$(P These equivalents hold when the D and C++ compilers used are companions
on the host platform.)
$(H3 $(LNAME2 dynamic-arrays, Dynamic Arrays))
$(P These are not supported for `extern (C++)`. For `extern (C)`, they
are equivalent to a struct template. For example:)
---
extern (C) const(char)[] slice;
---
$(P `dmd -HC` generates the following C++ declaration:)
```
extern "C" _d_dynamicArray< const char > slice;
```
$(P `_d_dynamicArray` is generated as follows:)
```
/// Represents a D [] array
template<typename T>
struct _d_dynamicArray final
{
size_t length;
T *ptr;
_d_dynamicArray() : length(0), ptr(NULL) { }
_d_dynamicArray(size_t length_in, T *ptr_in)
: length(length_in), ptr(ptr_in) { }
T& operator[](const size_t idx) {
assert(idx < length);
return ptr[idx];
}
const T& operator[](const size_t idx) const {
assert(idx < length);
return ptr[idx];
}
};
```
$(H2 $(LNAME2 packing-and-alignment, Packing and Alignment))
$(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)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.
)
$(P D supports bitfields in the standard library: see
$(REF bitfields, std, bitmanip).
)
$(H2 $(LNAME2 lifetime-management, Lifetime Management))
$(P C++ constructors, copy constructors, and destructors can be called directly in D code.
C++ move constructors cannot be called directly in D code.
)
$(P In a foo.cpp file: )
$(CPPLISTING
#include $(LT)iostream$(GT)
using namespace std;
class A
{
public:
A(int i);
~A();
};
A::A(int i)
{
cout << "calling C++ integer constructor " << endl;
}
A::~A()
{
cout << "calling C++ destructor " << endl;
}
)
$(P In a bar.d file: )
------
extern(C++) class A
{
this(int i);
~this();
}
void main()
{
auto obj1 = new A(5); // calls the constructor
destroy!false(obj1); //calls the destructor
}
------
$(P Compiling, linking, and running produces the output:)
$(CONSOLE
$(GT) g++ -c foo.cpp
$(GT) dmd bar.d foo.o -L-lstdc++ && ./bar
calling C++ integer constructor
calling C++ destructor
)
$(P Note that the C++ Copy constructor cannot be called using D classes since classes in D are reference types.
Value semantics are needed to be able to copy, so use a D struct.)
$(P In a foo.cpp file: )