-
Notifications
You must be signed in to change notification settings - Fork 526
/
Copy pathCSharpMarshal.cs
979 lines (859 loc) · 42.3 KB
/
CSharpMarshal.cs
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
using System.Linq;
using CppSharp.AST;
using CppSharp.AST.Extensions;
using CppSharp.Generators.C;
using CppSharp.Types;
using Type = CppSharp.AST.Type;
namespace CppSharp.Generators.CSharp
{
public class CSharpMarshalContext : MarshalContext
{
public CSharpMarshalContext(BindingContext context, uint indentation)
: base(context, indentation)
{
}
public bool HasCodeBlock { get; set; }
}
public abstract class CSharpMarshalPrinter : MarshalPrinter<CSharpMarshalContext, CSharpTypePrinter>
{
protected CSharpMarshalPrinter(CSharpMarshalContext context)
: base(context)
{
VisitOptions.ClearFlags(VisitFlags.FunctionParameters |
VisitFlags.TemplateArguments);
}
public override bool VisitMemberPointerType(MemberPointerType member,
TypeQualifiers quals)
{
return false;
}
}
public class CSharpMarshalNativeToManagedPrinter : CSharpMarshalPrinter
{
public CSharpMarshalNativeToManagedPrinter(CSharpMarshalContext context)
: base(context)
{
}
public override bool VisitType(Type type, TypeQualifiers quals)
{
TypeMap typeMap;
if (Context.Context.TypeMaps.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling)
{
typeMap.CSharpMarshalToManaged(Context);
return false;
}
return true;
}
public override bool VisitDeclaration(Declaration decl) => true;
public override bool VisitArrayType(ArrayType array, TypeQualifiers quals)
{
if (!VisitType(array, quals))
return false;
switch (array.SizeType)
{
case ArrayType.ArraySize.Constant:
if (Context.MarshalKind != MarshalKind.NativeField &&
Context.MarshalKind != MarshalKind.ReturnVariableArray)
goto case ArrayType.ArraySize.Incomplete;
var arrayType = array.Type.Desugar();
if (CheckIfArrayCanBeCopiedUsingMemoryCopy(array))
{
if (Context.Context.Options.UseSpan)
Context.Return.Write($"new Span<{arrayType}>({Context.ReturnVarName}, {array.Size})");
else
Context.Return.Write($"CppSharp.Runtime.MarshalUtil.GetArray<{arrayType}>({Context.ReturnVarName}, {array.Size})");
}
else if (array.Type.IsPrimitiveType(PrimitiveType.Char) && Context.Context.Options.MarshalCharAsManagedChar)
Context.Return.Write($"CppSharp.Runtime.MarshalUtil.GetCharArray({Context.ReturnVarName}, {array.Size})");
else if (array.Type.IsPointerToPrimitiveType(PrimitiveType.Void))
if (Context.Context.Options.UseSpan)
Context.Return.Write($"Span<IntPtr>({Context.ReturnVarName}, {array.Size})");
else
Context.Return.Write($"CppSharp.Runtime.MarshalUtil.GetIntPtrArray({Context.ReturnVarName}, {array.Size})");
else
{
string value = Generator.GeneratedIdentifier("value");
var supportBefore = Context.Before;
supportBefore.WriteLine($"{arrayType}[] {value} = null;");
supportBefore.WriteLine($"if ({Context.ReturnVarName} != null)");
supportBefore.WriteOpenBraceAndIndent();
supportBefore.WriteLine($"{value} = new {arrayType}[{array.Size}];");
supportBefore.WriteLine($"for (int i = 0; i < {array.Size}; i++)");
var finalArrayType = arrayType.GetPointee() ?? arrayType;
Class @class;
if (finalArrayType.TryGetClass(out @class) && @class.IsRefType)
{
if (arrayType == finalArrayType)
supportBefore.WriteLineIndent(
"{0}[i] = {1}.{2}((IntPtr)(({1}.{3}*)&({4}[i * sizeof({1}.{3})])), true, true);",
value, array.Type, Helpers.GetOrCreateInstanceIdentifier,
Helpers.InternalStruct, Context.ReturnVarName);
else
supportBefore.WriteLineIndent(
$@"{value}[i] = {finalArrayType}.{Helpers.CreateInstanceIdentifier}(({
typePrinter.IntPtrType}) {Context.ReturnVarName}[i]);");
}
else
{
supportBefore.WriteLineIndent($"{value}[i] = {Context.ReturnVarName}[i];");
}
supportBefore.UnindentAndWriteCloseBrace();
Context.Return.Write(value);
}
break;
case ArrayType.ArraySize.Incomplete:
// const char* and const char[] are the same so we can use a string
if (Context.Context.Options.MarshalConstCharArrayAsString &&
array.Type.Desugar().IsPrimitiveType(PrimitiveType.Char) &&
array.QualifiedType.Qualifiers.IsConst)
{
var pointer = new PointerType { QualifiedPointee = array.QualifiedType };
Context.ReturnType = new QualifiedType(pointer);
return this.VisitPointerType(pointer, quals);
}
MarshalArray(array);
break;
case ArrayType.ArraySize.Variable:
Context.Return.Write(Context.ReturnVarName);
break;
}
return true;
}
public override bool VisitPointerType(PointerType pointer, TypeQualifiers quals)
{
if (!VisitType(pointer, quals))
return false;
var param = Context.Parameter;
var isRefParam = param != null && (param.IsInOut || param.IsOut);
var pointee = pointer.Pointee.Desugar();
var finalPointee = pointer.GetFinalPointee().Desugar();
var returnType = Context.ReturnType.Type.Desugar(
resolveTemplateSubstitution: false);
if ((pointee.IsConstCharString() && (isRefParam || returnType.IsReference())) ||
(!finalPointee.IsPrimitiveType(out PrimitiveType primitive) &&
!finalPointee.IsEnumType()))
{
if (Context.MarshalKind != MarshalKind.NativeField &&
pointee.IsPointerTo(out Type type) &&
type.Desugar().TryGetClass(out Class c))
{
string ret = Generator.GeneratedIdentifier(Context.ReturnVarName);
Context.Before.WriteLine($@"{typePrinter.IntPtrType} {ret} = {
Context.ReturnVarName} == {typePrinter.IntPtrType}.Zero ? {
typePrinter.IntPtrType}.Zero : new {
typePrinter.IntPtrType}(*(void**) {Context.ReturnVarName});");
Context.ReturnVarName = ret;
}
return pointer.QualifiedPointee.Visit(this);
}
if (isRefParam)
{
Context.Return.Write(Generator.GeneratedIdentifier(param.Name));
return true;
}
if (Context.Context.Options.MarshalCharAsManagedChar &&
primitive == PrimitiveType.Char)
Context.Return.Write($"({pointer}) ");
if (Context.Function != null &&
Context.Function.OperatorKind == CXXOperatorKind.Subscript)
{
if (returnType.IsPrimitiveType(primitive))
{
Context.Return.Write("*");
}
else
{
var substitution = pointer.Pointee.Desugar(
resolveTemplateSubstitution: false) as TemplateParameterSubstitutionType;
if (substitution != null)
Context.Return.Write($@"({
substitution.ReplacedParameter.Parameter.Name}) (object) *");
}
}
if (new QualifiedType(pointer, quals).IsConstRefToPrimitive())
{
Context.Return.Write("*");
if (Context.MarshalKind == MarshalKind.NativeField)
Context.Return.Write($"({pointer.QualifiedPointee.Visit(typePrinter)}*) ");
}
Context.Return.Write(Context.ReturnVarName);
return true;
}
public override bool VisitPrimitiveType(PrimitiveType primitive, TypeQualifiers quals)
{
switch (primitive)
{
case PrimitiveType.Void:
return true;
case PrimitiveType.Bool:
if (Context.MarshalKind == MarshalKind.NativeField)
{
// returned structs must be blittable and bool isn't
Context.Return.Write("{0} != 0", Context.ReturnVarName);
return true;
}
goto default;
default:
Context.Return.Write(Context.ReturnVarName);
return true;
}
}
public override bool VisitTypedefType(TypedefType typedef, TypeQualifiers quals)
{
if (!(typedef.Declaration.Type.Desugar(false) is TemplateParameterSubstitutionType) &&
!VisitType(typedef, quals))
return false;
var decl = typedef.Declaration;
Type type = decl.Type.Desugar();
var functionType = type as FunctionType;
if (functionType == null && !type.IsPointerTo(out functionType))
return decl.Type.Visit(this);
var ptrName = $@"{Generator.GeneratedIdentifier("ptr")}{
Context.ParameterIndex}";
Context.Before.WriteLine($"var {ptrName} = {Context.ReturnVarName};");
var substitution = decl.Type.Desugar(false)
as TemplateParameterSubstitutionType;
if (substitution != null)
Context.Return.Write($@"({
substitution.ReplacedParameter.Parameter.Name}) (object) (");
Context.Return.Write($@"{ptrName} == IntPtr.Zero? null : {
(substitution == null ? $"({Context.ReturnType}) " :
string.Empty)}Marshal.GetDelegateForFunctionPointer({
ptrName}, typeof({typedef}))");
if (substitution != null)
Context.Return.Write(")");
return true;
}
public override bool VisitFunctionType(FunctionType function, TypeQualifiers quals)
{
var ptrName = Generator.GeneratedIdentifier("ptr") + Context.ParameterIndex;
Context.Before.WriteLine("var {0} = {1};", ptrName,
Context.ReturnVarName);
Context.Return.Write("({1})Marshal.GetDelegateForFunctionPointer({0}, typeof({1}))",
ptrName, function.ToString());
return true;
}
public override bool VisitClassDecl(Class @class)
{
var originalClass = @class.OriginalClass ?? @class;
Type returnType = Context.ReturnType.Type.Desugar();
// if the class is an abstract impl, use the original for the object map
var qualifiedClass = originalClass.Visit(typePrinter);
var finalType = (returnType.GetFinalPointee() ?? returnType).Desugar();
Class returnedClass;
if (finalType.TryGetClass(out returnedClass) && returnedClass.IsDependent)
Context.Return.Write($"({returnType.Visit(typePrinter)}) (object) ");
// these two aren't the same for members of templates
if (Context.Function?.OriginalReturnType.Type.Desugar().IsAddress() == true ||
returnType.IsAddress())
Context.Return.Write(HandleReturnedPointer(@class, qualifiedClass));
else
{
if (Context.MarshalKind == MarshalKind.NativeField ||
Context.MarshalKind == MarshalKind.Variable ||
Context.MarshalKind == MarshalKind.ReturnVariableArray ||
!originalClass.HasNonTrivialDestructor)
{
Context.Return.Write($"{qualifiedClass}.{Helpers.CreateInstanceIdentifier}({Context.ReturnVarName})");
}
else
{
Context.Before.WriteLine($@"var __{Context.ReturnVarName} = {
qualifiedClass}.{Helpers.CreateInstanceIdentifier}({Context.ReturnVarName});");
Method dtor = originalClass.Destructors.First();
if (dtor.IsVirtual)
{
var i = VTables.GetVTableIndex(dtor);
int vtableIndex = 0;
if (Context.Context.ParserOptions.IsMicrosoftAbi)
vtableIndex = @class.Layout.VFTables.IndexOf(@class.Layout.VFTables.First(
v => v.Layout.Components.Any(c => c.Method == dtor)));
string instance = $"new {typePrinter.IntPtrType}(&{Context.ReturnVarName})";
Context.Before.WriteLine($@"var __vtables = new IntPtr[] {{ {
string.Join(", ", originalClass.Layout.VTablePointers.Select(
x => $"*({typePrinter.IntPtrType}*) ({instance} + {x.Offset})"))} }};");
Context.Before.WriteLine($@"var __slot = *({typePrinter.IntPtrType}*) (__vtables[{
vtableIndex}] + {i} * sizeof({typePrinter.IntPtrType}));");
Context.Before.Write($"Marshal.GetDelegateForFunctionPointer<{dtor.FunctionType}>(__slot)({instance}");
if (dtor.GatherInternalParams(Context.Context.ParserOptions.IsItaniumLikeAbi).Count > 1)
{
Context.Before.Write(", 0");
}
Context.Before.WriteLine(");");
}
else
{
string suffix = string.Empty;
var specialization = @class as ClassTemplateSpecialization;
if (specialization != null)
suffix = Helpers.GetSuffixFor(specialization);
Context.Before.WriteLine($@"{typePrinter.PrintNative(originalClass)}.dtor{
suffix}(new {typePrinter.IntPtrType}(&{Context.ReturnVarName}));");
}
Context.Return.Write($"__{Context.ReturnVarName}");
}
}
return true;
}
public override bool VisitEnumDecl(Enumeration @enum)
{
Context.Return.Write("{0}", Context.ReturnVarName);
return true;
}
public override bool VisitParameterDecl(Parameter parameter)
{
if (parameter.Usage == ParameterUsage.Unknown || parameter.IsIn)
return base.VisitParameterDecl(parameter);
var ctx = new CSharpMarshalContext(Context.Context, Context.Indentation)
{
ReturnType = Context.ReturnType,
ReturnVarName = Context.ReturnVarName
};
var marshal = new CSharpMarshalNativeToManagedPrinter(ctx);
parameter.Type.Visit(marshal);
if (!string.IsNullOrWhiteSpace(ctx.Before))
Context.Before.WriteLine(ctx.Before);
if (!string.IsNullOrWhiteSpace(ctx.Return) &&
!parameter.Type.IsPrimitiveTypeConvertibleToRef())
{
Context.Before.WriteLine("var _{0} = {1};", parameter.Name,
ctx.Return);
}
Context.Return.Write("{0}{1}",
parameter.Type.IsPrimitiveTypeConvertibleToRef() ? "ref *" : "_", parameter.Name);
return true;
}
public override bool VisitTemplateParameterSubstitutionType(TemplateParameterSubstitutionType param, TypeQualifiers quals)
{
Type returnType = Context.ReturnType.Type.Desugar();
Type finalType = (returnType.GetFinalPointee() ?? returnType).Desugar();
if (finalType.IsDependent)
Context.Return.Write($"({param.ReplacedParameter.Parameter.Name}) (object) ");
Type replacement = param.Replacement.Type.Desugar();
if (replacement.IsPointerToPrimitiveType() && !replacement.IsConstCharString())
Context.Return.Write($"({typePrinter.IntPtrType}) ");
return base.VisitTemplateParameterSubstitutionType(param, quals);
}
private string HandleReturnedPointer(Class @class, string qualifiedClass)
{
var originalClass = @class.OriginalClass ?? @class;
var ret = Generator.GeneratedIdentifier("result") + Context.ParameterIndex;
if (originalClass.IsRefType)
{
var dtor = originalClass.Destructors.FirstOrDefault();
var dtorVirtual = (dtor != null && dtor.IsVirtual);
var cache = dtorVirtual && Context.Parameter == null;
var skipVTables = dtorVirtual && Context.Parameter != null;
var get = Context.Context.Options.GenerateNativeToManagedFor(@class) ? "GetOr" : "";
Context.Before.WriteLine("var {0} = {1}.__{5}CreateInstance({2}, {3}{4});",
ret, qualifiedClass, Context.ReturnVarName, cache ? "true" : "false", skipVTables ? ", skipVTables: true" : string.Empty, get);
}
else
{
Context.Before.WriteLine("var {0} = {1} != IntPtr.Zero ? {2}.{3}({4}) : default;",
ret, Context.ReturnVarName, qualifiedClass, Helpers.CreateInstanceIdentifier, Context.ReturnVarName);
}
return ret;
}
private void MarshalArray(ArrayType array)
{
Type arrayType = array.Type.Desugar();
if (arrayType.IsPrimitiveType() ||
arrayType.IsPointerToPrimitiveType() ||
Context.MarshalKind != MarshalKind.GenericDelegate)
{
Context.Return.Write(Context.ReturnVarName);
return;
}
var intermediateArray = Generator.GeneratedIdentifier(Context.ReturnVarName);
var intermediateArrayType = arrayType.Visit(typePrinter);
Context.Before.WriteLine($"{intermediateArrayType}[] {intermediateArray};");
Context.Before.WriteLine($"if ({Context.ReturnVarName} is null)");
Context.Before.WriteLineIndent($"{intermediateArray} = null;");
Context.Before.WriteLine("else");
Context.Before.WriteOpenBraceAndIndent();
Context.Before.WriteLine($@"{intermediateArray} = new {
intermediateArrayType}[{Context.ReturnVarName}.Length];");
Context.Before.WriteLine($"for (int i = 0; i < {intermediateArray}.Length; i++)");
if (arrayType.IsAddress())
{
Context.Before.WriteOpenBraceAndIndent();
string element = Generator.GeneratedIdentifier("element");
Context.Before.WriteLine($"var {element} = {Context.ReturnVarName}[i];");
var intPtrZero = $"{typePrinter.IntPtrType}.Zero";
Context.Before.WriteLine($@"{intermediateArray}[i] = {element} == {
intPtrZero} ? null : {intermediateArrayType}.{
Helpers.CreateInstanceIdentifier}({element});");
Context.Before.UnindentAndWriteCloseBrace();
}
else
Context.Before.WriteLineIndent($@"{intermediateArray}[i] = {
intermediateArrayType}.{Helpers.CreateInstanceIdentifier}({
Context.ReturnVarName}[i]);");
Context.Before.UnindentAndWriteCloseBrace();
Context.Return.Write(intermediateArray);
}
public bool CheckIfArrayCanBeCopiedUsingMemoryCopy(ArrayType array)
{
return array.Type.IsPrimitiveType(out var primitive) &&
(!Context.Context.Options.MarshalCharAsManagedChar || primitive != PrimitiveType.Char);
}
}
public class CSharpMarshalManagedToNativePrinter : CSharpMarshalPrinter
{
public CSharpMarshalManagedToNativePrinter(CSharpMarshalContext context)
: base(context)
{
}
public override bool VisitType(Type type, TypeQualifiers quals)
{
TypeMap typeMap;
if (Context.Context.TypeMaps.FindTypeMap(type, out typeMap) && typeMap.DoesMarshalling)
{
typeMap.CSharpMarshalToNative(Context);
return false;
}
return true;
}
public override bool VisitDeclaration(Declaration decl) => true;
public override bool VisitArrayType(ArrayType array, TypeQualifiers quals)
{
if (!VisitType(array, quals))
return false;
switch (array.SizeType)
{
case ArrayType.ArraySize.Constant:
if (string.IsNullOrEmpty(Context.ReturnVarName))
goto case ArrayType.ArraySize.Incomplete;
var supportBefore = Context.Before;
supportBefore.WriteLine($"if ({Context.ArgName} != null)");
supportBefore.WriteOpenBraceAndIndent();
Class @class;
var arrayType = array.Type.Desugar();
var finalArrayType = arrayType.GetPointee() ?? arrayType;
if (finalArrayType.TryGetClass(out @class) && @class.IsRefType)
{
supportBefore.WriteLine($"if (value.Length != {array.Size})");
ThrowArgumentOutOfRangeException();
}
supportBefore.WriteLine($"for (int i = 0; i < {array.Size}; i++)");
if (@class != null && @class.IsRefType)
{
if (finalArrayType == arrayType)
supportBefore.WriteLineIndent(
"*({1}.{2}*) &{0}[i * sizeof({1}.{2})] = *({1}.{2}*){3}[i].{4};",
Context.ReturnVarName, arrayType, Helpers.InternalStruct,
Context.ArgName, Helpers.InstanceIdentifier);
else
supportBefore.WriteLineIndent($@"{Context.ReturnVarName}[i] = ({
(Context.Context.TargetInfo.PointerWidth == 64 ? "long" : "int")}) {
Context.ArgName}[i].{Helpers.InstanceIdentifier};");
}
else
{
if (arrayType.IsPrimitiveType(PrimitiveType.Bool))
supportBefore.WriteLineIndent($@"{
Context.ReturnVarName}[i] = (byte)({
Context.ArgName}[i] ? 1 : 0);");
else if (arrayType.IsPrimitiveType(PrimitiveType.Char) &&
Context.Context.Options.MarshalCharAsManagedChar)
supportBefore.WriteLineIndent($@"{
Context.ReturnVarName}[i] = global::System.Convert.ToSByte({
Context.ArgName}[i]);");
else
supportBefore.WriteLineIndent($@"{Context.ReturnVarName}[i] = {
Context.ArgName}[i]{
(arrayType.IsPointerToPrimitiveType(PrimitiveType.Void) ?
".ToPointer()" : string.Empty)};");
}
supportBefore.UnindentAndWriteCloseBrace();
break;
case ArrayType.ArraySize.Incomplete:
MarshalArray(array);
break;
default:
Context.Return.Write("null");
break;
}
return true;
}
public override bool VisitPointerType(PointerType pointer, TypeQualifiers quals)
{
if (!VisitType(pointer, quals))
return false;
var param = Context.Parameter;
var isRefParam = param != null && (param.IsInOut || param.IsOut);
var pointee = pointer.Pointee.Desugar();
if (pointee.IsConstCharString())
{
if (param.IsOut)
{
MarshalString(pointee);
Context.Return.Write($"{typePrinter.IntPtrType}.Zero");
Context.ArgumentPrefix.Write("&");
return true;
}
if (param.IsInOut)
{
MarshalString(pointee);
pointer.QualifiedPointee.Visit(this);
Context.ArgumentPrefix.Write("&");
return true;
}
if (pointer.IsReference)
{
Context.Return.Write($@"({typePrinter.PrintNative(
pointee.GetQualifiedPointee())}*) ");
pointer.QualifiedPointee.Visit(this);
Context.ArgumentPrefix.Write("&");
return true;
}
}
var finalPointee = (pointee.GetFinalPointee() ?? pointee).Desugar();
if (finalPointee.IsPrimitiveType(out PrimitiveType primitive) ||
finalPointee.IsEnumType())
{
if (isRefParam)
{
var local = Generator.GeneratedIdentifier($@"{
param.Name}{Context.ParameterIndex}");
Context.Before.WriteLine($@"fixed ({
pointer.Visit(typePrinter)} {local} = &{param.Name})");
Context.HasCodeBlock = true;
Context.Before.WriteOpenBraceAndIndent();
Context.Return.Write(local);
return true;
}
bool isConst = quals.IsConst || pointer.QualifiedPointee.Qualifiers.IsConst ||
pointer.GetFinalQualifiedPointee().Qualifiers.IsConst;
if (Context.Context.Options.MarshalCharAsManagedChar &&
primitive == PrimitiveType.Char)
{
Context.Return.StringBuilder.Insert(0, $"({typePrinter.PrintNative(pointer)}) ");
if (isConst)
Context.Return.Write("&");
Context.Return.Write(param.Name);
return true;
}
pointer.QualifiedPointee.Visit(this);
if (Context.Parameter.IsIndirect)
Context.ArgumentPrefix.Write("&");
bool isVoid = primitive == PrimitiveType.Void && pointer.IsReference() && isConst;
if (pointer.Pointee.Desugar(false) is TemplateParameterSubstitutionType || isVoid)
{
var local = Generator.GeneratedIdentifier($@"{
param.Name}{Context.ParameterIndex}");
Context.Before.WriteLine($"var {local} = {Context.Return};");
Context.Return.StringBuilder.Clear();
Context.Return.Write(local);
}
if (new QualifiedType(pointer, quals).IsConstRefToPrimitive())
Context.Return.StringBuilder.Insert(0, '&');
return true;
}
string arg = Generator.GeneratedIdentifier(Context.ArgName);
if (pointee.TryGetClass(out Class @class) && @class.IsValueType)
{
if (Context.Parameter.Usage == ParameterUsage.Out)
{
Context.Before.WriteLine("fixed ({0}.{1}* {2} = &{3}.{4})",
Context.Parameter.QualifiedType, Helpers.InternalStruct,
arg, Context.Parameter.Name, Helpers.InstanceIdentifier);
Context.HasCodeBlock = true;
Context.Before.WriteOpenBraceAndIndent();
Context.Return.Write($"new {typePrinter.IntPtrType}({arg})");
}
else
{
Context.Before.Write($"var {arg} = ");
if (pointer.Pointee.IsTemplateParameterType())
Context.Before.Write($"(({Context.Parameter.Type}) (object) {Context.Parameter.Name})");
else
Context.Before.Write(Context.Parameter.Name);
Context.Before.WriteLine($".{Helpers.InstanceIdentifier};");
Context.Return.Write($"new {typePrinter.IntPtrType}(&{arg})");
}
return true;
}
if (pointee.IsPointerTo(out Type type) &&
type.Desugar().TryGetClass(out Class c))
{
pointer.QualifiedPointee.Visit(this);
Context.Before.WriteLine($"var {arg} = {Context.Return};");
Context.Return.StringBuilder.Clear();
Context.Return.Write($"new {typePrinter.IntPtrType}(&{arg})");
return true;
}
return pointer.QualifiedPointee.Visit(this);
}
public override bool VisitPrimitiveType(PrimitiveType primitive, TypeQualifiers quals)
{
switch (primitive)
{
case PrimitiveType.Bool:
if (Context.MarshalKind == MarshalKind.NativeField)
{
// returned structs must be blittable and bool isn't
Context.Return.Write("(byte) ({0} ? 1 : 0)", Context.Parameter.Name);
return true;
}
goto default;
default:
Context.Return.Write(Context.Parameter.Name);
return true;
}
}
public override bool VisitTypedefType(TypedefType typedef, TypeQualifiers quals)
{
if (!VisitType(typedef, quals))
return false;
return typedef.Declaration.Type.Visit(this);
}
public override bool VisitTemplateParameterSubstitutionType(TemplateParameterSubstitutionType param, TypeQualifiers quals)
{
var replacement = param.Replacement.Type.Desugar();
if ((replacement.IsPrimitiveType() ||
replacement.IsPointerToPrimitiveType() ||
replacement.IsEnum()) &&
!replacement.IsConstCharString())
{
Context.Return.Write($"({replacement}) ");
if (replacement.IsPointerToPrimitiveType())
Context.Return.Write($"({typePrinter.IntPtrType}) ");
Context.Return.Write("(object) ");
}
return base.VisitTemplateParameterSubstitutionType(param, quals);
}
public override bool VisitTemplateParameterType(TemplateParameterType param, TypeQualifiers quals)
{
Context.Return.Write(param.Parameter.Name);
return true;
}
public override bool VisitClassDecl(Class @class)
{
if (!VisitDeclaration(@class))
return false;
if (@class.IsValueType)
{
MarshalValueClass();
}
else
{
MarshalRefClass(@class);
}
return true;
}
private void MarshalRefClass(Class @class)
{
var method = Context.Function as Method;
string param = Context.Parameter.Name;
Type type = Context.Parameter.Type.Desugar(resolveTemplateSubstitution: false);
string paramInstance;
Class @interface;
var finalType = type.GetFinalPointee() ?? type;
var templateType = finalType as TemplateParameterSubstitutionType;
type = Context.Parameter.Type.Desugar();
if (templateType != null)
param = $"(({@class.Visit(typePrinter)}) (object) {param})";
if (finalType.TryGetClass(out @interface) &&
@interface.IsInterface)
paramInstance = $"{param}.__PointerTo{@interface.OriginalClass.Name}";
else
paramInstance = $"{param}.{Helpers.InstanceIdentifier}";
if (!type.IsAddress())
{
Context.Before.WriteLine($"if (ReferenceEquals({Context.Parameter.Name}, null))");
Context.Before.WriteLineIndent(
$@"throw new global::System.ArgumentNullException(""{
Context.Parameter.Name}"", ""Cannot be null because it is passed by value."");");
var realClass = @class.OriginalClass ?? @class;
var qualifiedIdentifier = typePrinter.PrintNative(realClass);
Context.ArgumentPrefix.Write($"*({qualifiedIdentifier}*) ");
Context.Return.Write(paramInstance);
return;
}
Class decl;
if (type.TryGetClass(out decl) && decl.IsValueType)
{
Context.Return.Write(paramInstance);
return;
}
if (type.IsPointer())
{
if (Context.Parameter.IsIndirect)
{
Context.Before.WriteLine($"if (ReferenceEquals({Context.Parameter.Name}, null))");
Context.Before.WriteLineIndent(
$@"throw new global::System.ArgumentNullException(""{
Context.Parameter.Name}"", ""Cannot be null because it is passed by value."");");
Context.Return.Write(paramInstance);
}
else
{
Context.Return.Write("{0}{1}",
method != null && method.OperatorKind == CXXOperatorKind.EqualEqual
? string.Empty
: $"{param} is null ? {typePrinter.IntPtrType}.Zero : ",
paramInstance);
}
return;
}
if (method == null ||
// redundant for comparison operators, they are handled in a special way
(method.OperatorKind != CXXOperatorKind.EqualEqual &&
method.OperatorKind != CXXOperatorKind.ExclaimEqual))
{
Context.Before.WriteLine($"if (ReferenceEquals({Context.Parameter.Name}, null))");
Context.Before.WriteLineIndent(
$@"throw new global::System.ArgumentNullException(""{
Context.Parameter.Name}"", ""Cannot be null because it is a C++ reference (&)."");",
param);
}
Context.Return.Write(paramInstance);
}
private void MarshalValueClass()
{
if (Context.Parameter.Type.IsTemplateParameterType())
Context.Return.Write($"(({Context.Parameter.Type}) (object) {Context.Parameter.Name})");
else
Context.Return.Write(Context.Parameter.Name);
Context.Return.Write($".{Helpers.InstanceIdentifier}");
}
public override bool VisitFieldDecl(Field field)
{
if (!VisitDeclaration(field))
return false;
Context.Parameter = new Parameter
{
Name = Context.ArgName,
QualifiedType = field.QualifiedType,
};
Context.Field = field;
var ret = field.Type.Visit(this, field.QualifiedType.Qualifiers);
Context.Field = null;
return ret;
}
public override bool VisitProperty(Property property)
{
if (!VisitDeclaration(property))
return false;
Context.Parameter = new Parameter
{
Name = Context.ArgName,
QualifiedType = property.QualifiedType
};
Context.Property = property;
var ret = base.VisitProperty(property);
Context.Property = null;
return ret;
}
public override bool VisitEnumDecl(Enumeration @enum)
{
Context.Return.Write(Context.Parameter.Name);
return true;
}
public override bool VisitClassTemplateDecl(ClassTemplate template)
{
return VisitClassDecl(template.TemplatedClass);
}
public override bool VisitFunctionType(FunctionType function, TypeQualifiers quals)
{
Context.Return.Write("{0} == null ? global::System.IntPtr.Zero : Marshal.GetFunctionPointerForDelegate({0})",
Context.Parameter.Name);
return true;
}
public override bool VisitFunctionTemplateDecl(FunctionTemplate template)
{
return template.TemplatedFunction.Visit(this);
}
private void ThrowArgumentOutOfRangeException()
{
Context.Before.WriteLineIndent(
"throw new ArgumentOutOfRangeException(\"{0}\", " +
"\"The dimensions of the provided array don't match the required size.\");",
Context.Parameter.Name);
}
private void MarshalArray(ArrayType arrayType)
{
if (arrayType.SizeType == ArrayType.ArraySize.Constant)
{
Context.Before.WriteLine("if ({0} == null || {0}.Length != {1})",
Context.Parameter.Name, arrayType.Size);
ThrowArgumentOutOfRangeException();
}
var elementType = arrayType.Type.Desugar();
if ((elementType.IsPrimitiveType() &&
!(elementType.IsPrimitiveType(PrimitiveType.Char) && Context.Context.Options.MarshalCharAsManagedChar)) ||
elementType.IsPointerToPrimitiveType())
{
if (Context.Context.Options.UseSpan && !elementType.IsConstCharString())
{
var local = Generator.GeneratedIdentifier($@"{
Context.Parameter.Name}{Context.ParameterIndex}");
Context.Before.WriteLine($@"fixed ({
typePrinter.PrintNative(elementType)}* {local} = &MemoryMarshal.GetReference({Context.Parameter.Name}))");
Context.HasCodeBlock = true;
Context.Before.WriteOpenBraceAndIndent();
Context.Return.Write(local);
}
else
Context.Return.Write(Context.Parameter.Name);
return;
}
var intermediateArray = Generator.GeneratedIdentifier(Context.Parameter.Name);
var intermediateArrayType = typePrinter.PrintNative(elementType);
if (Context.Context.Options.UseSpan)
Context.Before.WriteLine($"Span<{intermediateArrayType}> {intermediateArray};");
else
Context.Before.WriteLine($"{intermediateArrayType}[] {intermediateArray};");
Context.Before.WriteLine($"if ({Context.Parameter.Name} == null)");
Context.Before.WriteLineIndent($"{intermediateArray} = null;");
Context.Before.WriteLine("else");
Context.Before.WriteOpenBraceAndIndent();
Context.Before.WriteLine($@"{intermediateArray} = new {
intermediateArrayType}[{Context.Parameter.Name}.Length];");
Context.Before.WriteLine($"for (int i = 0; i < {intermediateArray}.Length; i++)");
Context.Before.WriteOpenBraceAndIndent();
string element = Generator.GeneratedIdentifier("element");
Context.Before.WriteLine($"var {element} = {Context.Parameter.Name}[i];");
if (elementType.IsAddress())
{
var intPtrZero = $"{typePrinter.IntPtrType}.Zero";
Context.Before.WriteLine($@"{intermediateArray}[i] = {
element} is null ? {intPtrZero} : {element}.{Helpers.InstanceIdentifier};");
}
else if (elementType.IsPrimitiveType(PrimitiveType.Char) &&
Context.Context.Options.MarshalCharAsManagedChar)
Context.Before.WriteLine($@"{intermediateArray}[i] = global::System.Convert.ToSByte({
element});");
else
Context.Before.WriteLine($@"{intermediateArray}[i] = {
element} is null ? new {intermediateArrayType}() : *({
intermediateArrayType}*) {element}.{Helpers.InstanceIdentifier};");
Context.Before.UnindentAndWriteCloseBrace();
Context.Before.UnindentAndWriteCloseBrace();
if (Context.Context.Options.UseSpan)
{
var local = Generator.GeneratedIdentifier($@"{
intermediateArray}{Context.ParameterIndex}");
Context.Before.WriteLine($@"fixed ({
typePrinter.PrintNative(elementType)}* {local} = &MemoryMarshal.GetReference({intermediateArray}))");
Context.HasCodeBlock = true;
Context.Before.WriteOpenBraceAndIndent();
Context.Return.Write(local);
}
else
Context.Return.Write(intermediateArray);
}
private void MarshalString(Type pointee)
{
var marshal = new CSharpMarshalNativeToManagedPrinter(Context);
Context.ReturnVarName = Context.ArgName;
Context.ReturnType = Context.Parameter.QualifiedType;
pointee.Visit(marshal);
Context.Cleanup.WriteLine($@"{Context.Parameter.Name} = {
marshal.Context.Return};");
Context.Return.StringBuilder.Clear();
}
}
}