forked from QuantConnect/pythonnet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConverter.cs
More file actions
1421 lines (1238 loc) · 54.8 KB
/
Converter.cs
File metadata and controls
1421 lines (1238 loc) · 54.8 KB
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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;
using Python.Runtime.Native;
namespace Python.Runtime
{
/// <summary>
/// Performs data conversions between managed types and Python types.
/// </summary>
[SuppressUnmanagedCodeSecurity]
internal class Converter
{
private Converter()
{
}
private static NumberFormatInfo nfi;
private static Type objectType;
private static Type stringType;
private static Type singleType;
private static Type doubleType;
private static Type decimalType;
private static Type int16Type;
private static Type int32Type;
private static Type int64Type;
private static Type flagsType;
private static Type boolType;
private static Type typeType;
private static PyObject dateTimeCtor;
private static PyObject timeSpanCtor;
private static Lazy<PyObject> tzInfoCtor;
private static PyObject pyTupleNoKind;
private static PyObject pyTupleKind;
private static StrPtr yearPtr;
private static StrPtr monthPtr;
private static StrPtr dayPtr;
private static StrPtr hourPtr;
private static StrPtr minutePtr;
private static StrPtr secondPtr;
private static StrPtr microsecondPtr;
private static StrPtr tzinfoPtr;
private static StrPtr hoursPtr;
private static StrPtr minutesPtr;
static Converter()
{
nfi = NumberFormatInfo.InvariantInfo;
objectType = typeof(Object);
stringType = typeof(String);
int16Type = typeof(Int16);
int32Type = typeof(Int32);
int64Type = typeof(Int64);
singleType = typeof(Single);
doubleType = typeof(Double);
decimalType = typeof(Decimal);
flagsType = typeof(FlagsAttribute);
boolType = typeof(Boolean);
typeType = typeof(Type);
var dateTimeMod = Runtime.PyImport_ImportModule("datetime");
PythonException.ThrowIfIsNull(dateTimeMod);
dateTimeCtor = Runtime.PyObject_GetAttrString(dateTimeMod.Borrow(), "datetime").MoveToPyObject();
PythonException.ThrowIfIsNull(dateTimeCtor);
timeSpanCtor = Runtime.PyObject_GetAttrString(dateTimeMod.Borrow(), "timedelta").MoveToPyObject();
PythonException.ThrowIfIsNull(timeSpanCtor);
tzInfoCtor = new Lazy<PyObject>(() =>
{
var tzInfoMod = PyModule.FromString("custom_tzinfo", @"
from datetime import timedelta, tzinfo
class GMT(tzinfo):
def __init__(self, hours, minutes):
self.hours = hours
self.minutes = minutes
def utcoffset(self, dt):
return timedelta(hours=self.hours, minutes=self.minutes)
def tzname(self, dt):
return f'GMT {self.hours:00}:{self.minutes:00}'
def dst (self, dt):
return timedelta(0)").BorrowNullable();
var result = Runtime.PyObject_GetAttrString(tzInfoMod, "GMT").MoveToPyObject();
PythonException.ThrowIfIsNull(result);
return result;
});
pyTupleNoKind = Runtime.PyTuple_New(7).MoveToPyObject();
pyTupleKind = Runtime.PyTuple_New(8).MoveToPyObject();
yearPtr = new StrPtr("year", Encoding.UTF8);
monthPtr = new StrPtr("month", Encoding.UTF8);
dayPtr = new StrPtr("day", Encoding.UTF8);
hourPtr = new StrPtr("hour", Encoding.UTF8);
minutePtr = new StrPtr("minute", Encoding.UTF8);
secondPtr = new StrPtr("second", Encoding.UTF8);
microsecondPtr = new StrPtr("microsecond", Encoding.UTF8);
tzinfoPtr = new StrPtr("tzinfo", Encoding.UTF8);
hoursPtr = new StrPtr("hours", Encoding.UTF8);
minutesPtr = new StrPtr("minutes", Encoding.UTF8);
}
/// <summary>
/// Given a builtin Python type, return the corresponding CLR type.
/// </summary>
internal static Type? GetTypeByAlias(BorrowedReference op)
{
if (op == Runtime.PyStringType)
return stringType;
if (op == Runtime.PyUnicodeType)
return stringType;
if (op == Runtime.PyLongType)
return int32Type;
if (op == Runtime.PyLongType)
return int64Type;
if (op == Runtime.PyFloatType)
return doubleType;
if (op == Runtime.PyBoolType)
return boolType;
if (op == Runtime.PyDecimalType.Value)
return decimalType;
return null;
}
internal static BorrowedReference GetPythonTypeByAlias(Type op)
{
if (op == stringType)
return Runtime.PyUnicodeType.Reference;
if (op == int16Type)
return Runtime.PyLongType.Reference;
if (op == int32Type)
return Runtime.PyLongType.Reference;
if (op == int64Type)
return Runtime.PyLongType.Reference;
if (op == doubleType)
return Runtime.PyFloatType.Reference;
if (op == singleType)
return Runtime.PyFloatType.Reference;
if (op == boolType)
return Runtime.PyBoolType.Reference;
if (op == decimalType)
return Runtime.PyDecimalType.Value.Reference;
return BorrowedReference.Null;
}
/// <summary>
/// Return a Python object for the given native object, converting
/// basic types (string, int, etc.) into equivalent Python objects.
/// This always returns a new reference. Note that the System.Decimal
/// type has no Python equivalent and converts to a managed instance.
/// </summary>
internal static NewReference ToPython<T>(T value)
=> ToPython(value, typeof(T));
private static readonly Func<object, bool> IsTransparentProxy = GetIsTransparentProxy();
private static bool Never(object _) => false;
private static Func<object, bool> GetIsTransparentProxy()
{
var remoting = typeof(int).Assembly.GetType("System.Runtime.Remoting.RemotingServices");
if (remoting is null) return Never;
var isProxy = remoting.GetMethod("IsTransparentProxy", new[] { typeof(object) });
if (isProxy is null) return Never;
return (Func<object, bool>)Delegate.CreateDelegate(
typeof(Func<object, bool>), isProxy,
throwOnBindFailure: true);
}
internal static NewReference ToPythonDetectType(object? value)
=> value is null ? new NewReference(Runtime.PyNone) : ToPython(value, value.GetType());
internal static NewReference ToPython(object? value, Type type)
{
if (value is PyObject pyObj)
{
return new NewReference(pyObj);
}
// Null always converts to None in Python.
if (value == null)
{
return new NewReference(Runtime.PyNone);
}
type = value.GetType();
if (type.IsGenericType && value is IList && !(value is INotifyPropertyChanged))
{
using var resultlist = new PyList();
foreach (object o in (IEnumerable)value)
{
using var p = o.ToPython();
resultlist.Append(p);
}
return resultlist.NewReferenceOrNull();
}
// it the type is a python subclass of a managed type then return the
// underlying python object rather than construct a new wrapper object.
var pyderived = value as IPythonDerivedType;
if (null != pyderived)
{
if (!IsTransparentProxy(pyderived))
return ClassDerivedObject.ToPython(pyderived);
}
// hmm - from Python, we almost never care what the declared
// type is. we'd rather have the object bound to the actual
// implementing class.
TypeCode tc = Type.GetTypeCode(type);
switch (tc)
{
case TypeCode.Object:
if (value is TimeSpan)
{
var timespan = (TimeSpan)value;
using var timeSpanArgs = Runtime.PyTuple_New(1);
Runtime.PyTuple_SetItem(timeSpanArgs.Borrow(), 0, Runtime.PyFloat_FromDouble(timespan.TotalDays).Steal());
var returnTimeSpan = Runtime.PyObject_CallObject(timeSpanCtor, timeSpanArgs.Borrow());
return returnTimeSpan;
}
return CLRObject.GetReference(value, type);
case TypeCode.String:
return Runtime.PyString_FromString((string)value);
case TypeCode.Int32:
return Runtime.PyInt_FromInt32((int)value);
case TypeCode.Boolean:
if ((bool)value)
{
return new NewReference(Runtime.PyTrue);
}
return new NewReference(Runtime.PyFalse);
case TypeCode.Byte:
return Runtime.PyInt_FromInt32((int)((byte)value));
case TypeCode.Char:
return Runtime.PyUnicode_FromOrdinal((int)((char)value));
case TypeCode.Int16:
return Runtime.PyInt_FromInt32((int)((short)value));
case TypeCode.Int64:
return Runtime.PyLong_FromLongLong((long)value);
case TypeCode.Single:
return Runtime.PyFloat_FromDouble((float)value);
case TypeCode.Double:
return Runtime.PyFloat_FromDouble((double)value);
case TypeCode.SByte:
return Runtime.PyInt_FromInt32((int)((sbyte)value));
case TypeCode.UInt16:
return Runtime.PyInt_FromInt32((int)((ushort)value));
case TypeCode.UInt32:
return Runtime.PyLong_FromUnsignedLongLong((uint)value);
case TypeCode.UInt64:
return Runtime.PyLong_FromUnsignedLongLong((ulong)value);
case TypeCode.Decimal:
// C# decimal to python decimal has a big impact on performance
// so we will use C# double and python float
return Runtime.PyFloat_FromDouble(decimal.ToDouble((decimal)value));
case TypeCode.DateTime:
var datetime = (DateTime)value;
var size = datetime.Kind == DateTimeKind.Unspecified ? 7 : 8;
var dateTimeArgs = datetime.Kind == DateTimeKind.Unspecified ? pyTupleNoKind : pyTupleKind;
Runtime.PyTuple_SetItem(dateTimeArgs, 0, Runtime.PyInt_FromInt32(datetime.Year).Steal());
Runtime.PyTuple_SetItem(dateTimeArgs, 1, Runtime.PyInt_FromInt32(datetime.Month).Steal());
Runtime.PyTuple_SetItem(dateTimeArgs, 2, Runtime.PyInt_FromInt32(datetime.Day).Steal());
Runtime.PyTuple_SetItem(dateTimeArgs, 3, Runtime.PyInt_FromInt32(datetime.Hour).Steal());
Runtime.PyTuple_SetItem(dateTimeArgs, 4, Runtime.PyInt_FromInt32(datetime.Minute).Steal());
Runtime.PyTuple_SetItem(dateTimeArgs, 5, Runtime.PyInt_FromInt32(datetime.Second).Steal());
// datetime.datetime 6th argument represents micro seconds
var totalSeconds = datetime.TimeOfDay.TotalSeconds;
var microSeconds = Convert.ToInt32((totalSeconds - Math.Truncate(totalSeconds)) * 1000000);
if (microSeconds == 1000000) microSeconds = 999999;
Runtime.PyTuple_SetItem(dateTimeArgs, 6, Runtime.PyInt_FromInt32(microSeconds).Steal());
if (size == 8)
{
Runtime.PyTuple_SetItem(dateTimeArgs, 7, TzInfo(datetime.Kind).Steal());
}
var returnDateTime = Runtime.PyObject_CallObject(dateTimeCtor, dateTimeArgs);
return returnDateTime;
default:
if (value is IEnumerable)
{
using var resultlist = new PyList();
foreach (object o in (IEnumerable)value)
{
using var p = o.ToPython();
resultlist.Append(p);
}
return resultlist.NewReferenceOrNull();
}
return CLRObject.GetReference(value, type);
}
}
private static NewReference TzInfo(DateTimeKind kind)
{
if (kind == DateTimeKind.Unspecified) return new NewReference(Runtime.PyNone);
var offset = kind == DateTimeKind.Local ? DateTimeOffset.Now.Offset : TimeSpan.Zero;
using var tzInfoArgs = Runtime.PyTuple_New(2);
Runtime.PyTuple_SetItem(tzInfoArgs.Borrow(), 0, Runtime.PyLong_FromLongLong(offset.Hours).Steal());
Runtime.PyTuple_SetItem(tzInfoArgs.Borrow(), 1, Runtime.PyLong_FromLongLong(offset.Minutes).Steal());
var returnValue = Runtime.PyObject_CallObject(tzInfoCtor.Value, tzInfoArgs.Borrow());
return returnValue;
}
/// <summary>
/// In a few situations, we don't have any advisory type information
/// when we want to convert an object to Python.
/// </summary>
internal static NewReference ToPythonImplicit(object? value)
{
if (value == null)
{
return new NewReference(Runtime.PyNone);
}
return ToPython(value, objectType);
}
internal static bool ToManaged(BorrowedReference value, Type type,
out object? result, bool setError)
{
var usedImplicit = false;
return ToManaged(value, type, out result, setError, out usedImplicit);
}
/// <summary>
/// Return a managed object for the given Python object, taking funny
/// byref types into account.
/// </summary>
/// <param name="value">A Python object</param>
/// <param name="type">The desired managed type</param>
/// <param name="result">Receives the managed object</param>
/// <param name="setError">If true, call <c>Exceptions.SetError</c> with the reason for failure.</param>
/// <returns>True on success</returns>
internal static bool ToManaged(BorrowedReference value, Type type,
out object? result, bool setError, out bool usedImplicit)
{
if (type.IsByRef)
{
type = type.GetElementType();
}
return Converter.ToManagedValue(value, type, out result, setError, out usedImplicit);
}
internal static bool ToManagedValue(BorrowedReference value, Type obType,
out object result, bool setError)
{
var usedImplicit = false;
return ToManagedValue(value, obType, out result, setError, out usedImplicit);
}
internal static bool ToManagedValue(BorrowedReference value, Type obType,
out object? result, bool setError, out bool usedImplicit)
{
usedImplicit = false;
if (obType == typeof(PyObject))
{
result = new PyObject(value);
return true;
}
if (obType.IsGenericType && Runtime.PyObject_TYPE(value) == Runtime.PyListType)
{
var typeDefinition = obType.GetGenericTypeDefinition();
if (typeDefinition == typeof(List<>)
|| typeDefinition == typeof(IList<>)
|| typeDefinition == typeof(IEnumerable<>)
|| typeDefinition == typeof(IReadOnlyCollection<>)
|| typeDefinition == typeof(IReadOnlyList<>))
{
return ToList(value, obType, out result, setError);
}
}
// Common case: if the Python value is a wrapped managed object
// instance, just return the wrapped object.
var mt = ManagedType.GetManagedObject(value);
result = null;
if (mt != null)
{
if (mt is CLRObject co)
{
object tmp = co.inst;
var type = tmp.GetType();
if (obType.IsInstanceOfType(tmp) || IsSubclassOfRawGeneric(obType, type))
{
result = tmp;
return true;
}
else
{
// check implicit conversions that receive tmp type and return obType
var conversionMethod = type.GetMethod("op_Implicit", new[] { type });
if (conversionMethod != null && conversionMethod.ReturnType == obType)
{
try
{
result = conversionMethod.Invoke(null, new[] { tmp });
usedImplicit = true;
return true;
}
catch
{
// Failed to convert using implicit conversion, must catch the error to stop program from exploding on Linux
Exceptions.RaiseTypeError($"Failed to implicitly convert {type} to {obType}");
return false;
}
}
}
if (setError)
{
string typeString = tmp is null ? "null" : tmp.GetType().ToString();
Exceptions.SetError(Exceptions.TypeError, $"{typeString} value cannot be converted to {obType}");
}
return false;
}
if (mt is ClassBase cb)
{
// The value being converted is a class type, so it will only succeed if it's being converted into a Type
if (obType != typeof(Type))
{
return false;
}
if (!cb.type.Valid)
{
Exceptions.SetError(Exceptions.TypeError, cb.type.DeletedMessage);
return false;
}
result = cb.type.Value;
return true;
}
// shouldn't happen
return false;
}
if (value == Runtime.PyNone && !obType.IsValueType)
{
result = null;
return true;
}
if (obType.IsGenericType && obType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
if (value == Runtime.PyNone)
{
result = null;
return true;
}
// Set type to underlying type
obType = obType.GetGenericArguments()[0];
}
if (obType.ContainsGenericParameters)
{
if (setError)
{
Exceptions.SetError(Exceptions.TypeError, $"Cannot create an instance of the open generic type {obType}");
}
return false;
}
if (obType.IsArray)
{
return ToArray(value, obType, out result, setError);
}
if (obType.IsEnum)
{
return ToEnum(value, obType, out result, setError, out usedImplicit);
}
// Conversion to 'Object' is done based on some reasonable default
// conversions (Python string -> managed string, Python int -> Int32 etc.).
if (obType == objectType)
{
if (Runtime.IsStringType(value))
{
return ToPrimitive(value, stringType, out result, setError, out usedImplicit);
}
if (Runtime.PyBool_Check(value))
{
return ToPrimitive(value, boolType, out result, setError, out usedImplicit);
}
if (Runtime.PyInt_Check(value))
{
return ToPrimitive(value, int32Type, out result, setError, out usedImplicit);
}
if (Runtime.PyLong_Check(value))
{
return ToPrimitive(value, int64Type, out result, setError, out usedImplicit);
}
if (Runtime.PyFloat_Check(value))
{
return ToPrimitive(value, doubleType, out result, setError, out usedImplicit);
}
// give custom codecs a chance to take over conversion of sequences
var pyType = Runtime.PyObject_TYPE(value);
if (PyObjectConversions.TryDecode(value, pyType, obType, out result))
{
return true;
}
if (Runtime.PySequence_Check(value))
{
return ToArray(value, typeof(object[]), out result, setError);
}
result = new PyObject(value);
return true;
}
// Conversion to 'Type' is done using the same mappings as above for objects.
if (obType == typeType)
{
if (value == Runtime.PyStringType)
{
result = stringType;
return true;
}
if (value == Runtime.PyBoolType)
{
result = boolType;
return true;
}
if (value == Runtime.PyLongType)
{
result = int32Type;
return true;
}
if (value == Runtime.PyLongType)
{
result = int64Type;
return true;
}
if (value == Runtime.PyFloatType)
{
result = doubleType;
return true;
}
if (value == Runtime.PyListType || value == Runtime.PyTupleType)
{
result = typeof(object[]);
return true;
}
if (setError)
{
Exceptions.SetError(Exceptions.TypeError, "value cannot be converted to Type");
}
return false;
}
var underlyingType = Nullable.GetUnderlyingType(obType);
if (underlyingType != null)
{
return ToManagedValue(value, underlyingType, out result, setError, out usedImplicit);
}
TypeCode typeCode = Type.GetTypeCode(obType);
if (typeCode == TypeCode.Object)
{
var pyType = Runtime.PyObject_TYPE(value);
if (PyObjectConversions.TryDecode(value, pyType, obType, out result))
{
return true;
}
}
if (ToPrimitive(value, obType, out result, setError, out usedImplicit))
{
return true;
}
var opImplicit = obType.GetMethod("op_Implicit", new[] { obType });
if (opImplicit != null)
{
if (ToManagedValue(value, opImplicit.ReturnType, out result, setError, out usedImplicit))
{
opImplicit = obType.GetMethod("op_Implicit", new[] { result.GetType() });
if (opImplicit != null)
{
try
{
result = opImplicit.Invoke(null, new[] { result });
}
catch
{
// Failed to convert using implicit conversion, must catch the error to stop program from exploding on Linux
Exceptions.RaiseTypeError($"Failed to implicitly convert {result.GetType()} to {obType}");
return false;
}
}
return opImplicit != null;
}
}
return false;
}
/// <remarks>
/// Unlike <see cref="ToManaged(BorrowedReference, Type, out object?, bool)"/>,
/// this method does not have a <c>setError</c> parameter, because it should
/// only be called after <see cref="ToManaged(BorrowedReference, Type, out object?, bool)"/>.
/// </remarks>
internal static bool ToManagedExplicit(BorrowedReference value, Type obType,
out object? result)
{
result = null;
// this method would potentially clean any existing error resulting in information loss
Debug.Assert(Runtime.PyErr_Occurred() == null);
string? converterName =
IsInteger(obType) ? "__int__"
: IsFloatingNumber(obType) ? "__float__"
: null;
if (converterName is null) return false;
Debug.Assert(obType.IsPrimitive);
using var converter = Runtime.PyObject_GetAttrString(value, converterName);
if (converter.IsNull())
{
Exceptions.Clear();
return false;
}
using var explicitlyCoerced = Runtime.PyObject_CallObject(converter.Borrow(), BorrowedReference.Null);
if (explicitlyCoerced.IsNull())
{
Exceptions.Clear();
return false;
}
return ToPrimitive(explicitlyCoerced.Borrow(), obType, out result, false, out var _);
}
/// Determine if the comparing class is a subclass of a generic type
private static bool IsSubclassOfRawGeneric(Type generic, Type comparingClass)
{
// Check this is a raw generic type first
if (!generic.IsGenericType || !generic.ContainsGenericParameters)
{
return false;
}
// Ensure we have the full generic type definition or it won't match
generic = generic.GetGenericTypeDefinition();
// Loop for searching for generic match in inheritance tree of comparing class
// If we have reach null we don't have a match
while (comparingClass != null)
{
// Check the input for generic type definition, if doesn't exist just use the class
var comparingClassGeneric = comparingClass.IsGenericType ? comparingClass.GetGenericTypeDefinition() : null;
// If the same as generic, this is a subclass return true
if (generic == comparingClassGeneric)
{
return true;
}
// Step up the inheritance tree
comparingClass = comparingClass.BaseType;
}
// The comparing class is not based on the generic
return false;
}
internal delegate bool TryConvertFromPythonDelegate(BorrowedReference pyObj, out object? result);
internal static int ToInt32(BorrowedReference value)
{
nint num = Runtime.PyLong_AsSignedSize_t(value);
if (num == -1 && Exceptions.ErrorOccurred())
{
throw PythonException.ThrowLastAsClrException();
}
return checked((int)num);
}
/// <summary>
/// Convert a Python value to an instance of a primitive managed type.
/// </summary>
internal static bool ToPrimitive(BorrowedReference value, Type obType, out object result, bool setError, out bool usedImplicit)
{
result = null;
NewReference op = default;
usedImplicit = false;
TypeCode tc = Type.GetTypeCode(obType);
switch (tc)
{
case TypeCode.Object:
if (obType == typeof(TimeSpan))
{
op = Runtime.PyObject_Str(value);
TimeSpan ts;
var arr = Runtime.GetManagedString(op.Borrow()).Split(',');
op.Dispose();
string sts = arr.Length == 1 ? arr[0] : arr[1];
if (!TimeSpan.TryParse(sts, out ts))
{
goto type_error;
}
int days = 0;
if (arr.Length > 1)
{
if (!int.TryParse(arr[0].Split(' ')[0].Trim(), out days))
{
goto type_error;
}
}
result = ts.Add(TimeSpan.FromDays(days));
return true;
}
else if (obType.IsGenericType && obType.GetGenericTypeDefinition() == typeof(KeyValuePair<,>))
{
if (Runtime.PyDict_Check(value))
{
var typeArguments = obType.GenericTypeArguments;
if (typeArguments.Length != 2)
{
goto type_error;
}
BorrowedReference key, dicValue, pos;
// references returned through key, dicValue are borrowed.
if (Runtime.PyDict_Next(value, out pos, out key, out dicValue) != 0)
{
if (!ToManaged(key, typeArguments[0], out var convertedKey, setError, out usedImplicit))
{
goto type_error;
}
if (!ToManaged(dicValue, typeArguments[1], out var convertedValue, setError, out usedImplicit))
{
goto type_error;
}
result = Activator.CreateInstance(obType, convertedKey, convertedValue);
return true;
}
// and empty dictionary we can't create a key value pair from it
goto type_error;
}
}
break;
case TypeCode.String:
string st = Runtime.GetManagedString(value);
if (st == null)
{
goto type_error;
}
result = st;
return true;
case TypeCode.Int32:
{
// Python3 always use PyLong API
op = Runtime.PyNumber_Long(value);
if (op.IsNull() && Exceptions.ErrorOccurred())
{
goto convert_error;
}
nint num = Runtime.PyLong_AsSignedSize_t(op.Borrow());
op.Dispose();
if (num == -1 && Exceptions.ErrorOccurred())
{
goto convert_error;
}
if (num > Int32.MaxValue || num < Int32.MinValue)
{
goto overflow;
}
result = (int)num;
return true;
}
case TypeCode.Boolean:
if (value == Runtime.PyTrue)
{
result = true;
return true;
}
if (value == Runtime.PyFalse)
{
result = false;
return true;
}
if (setError)
{
goto type_error;
}
return false;
case TypeCode.Byte:
{
if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType))
{
if (Runtime.PyBytes_Size(value) == 1)
{
IntPtr bytePtr = Runtime.PyBytes_AsString(value);
result = (byte)Marshal.ReadByte(bytePtr);
return true;
}
goto type_error;
}
nint num = Runtime.PyLong_AsSignedSize_t(value);
if (num == -1 && Exceptions.ErrorOccurred())
{
goto convert_error;
}
if (num > Byte.MaxValue || num < Byte.MinValue)
{
goto overflow;
}
result = (byte)num;
return true;
}
case TypeCode.SByte:
{
if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType))
{
if (Runtime.PyBytes_Size(value) == 1)
{
IntPtr bytePtr = Runtime.PyBytes_AsString(value);
result = (sbyte)Marshal.ReadByte(bytePtr);
return true;
}
goto type_error;
}
nint num = Runtime.PyLong_AsSignedSize_t(value);
if (num == -1 && Exceptions.ErrorOccurred())
{
goto convert_error;
}
if (num > SByte.MaxValue || num < SByte.MinValue)
{
goto overflow;
}
result = (sbyte)num;
return true;
}
case TypeCode.Char:
{
if (Runtime.PyObject_TypeCheck(value, Runtime.PyBytesType))
{
if (Runtime.PyBytes_Size(value) == 1)
{
IntPtr bytePtr = Runtime.PyBytes_AsString(value);
result = (char)Marshal.ReadByte(bytePtr);
return true;
}
goto type_error;
}
else if (Runtime.PyObject_TypeCheck(value, Runtime.PyUnicodeType))
{
if (Runtime.PyUnicode_GetLength(value) == 1)
{
IntPtr unicodePtr = Runtime.PyUnicode_AsUnicode(value);
Char[] buff = new Char[1];
Marshal.Copy(unicodePtr, buff, 0, 1);
result = buff[0];
return true;
}
goto type_error;
}
nint num = Runtime.PyLong_AsSignedSize_t(value);
if (num == -1 && Exceptions.ErrorOccurred())
{
goto convert_error;
}
if (num > Char.MaxValue || num < Char.MinValue)
{
goto overflow;
}
result = (char)num;
return true;
}
case TypeCode.Int16:
{
op = Runtime.PyNumber_Long(value);
if ((op.IsNone() || op.IsNull()) && Exceptions.ErrorOccurred())
{
goto convert_error;
}
nint num = Runtime.PyLong_AsSignedSize_t(op.Borrow());
op.Dispose();
if (num == -1 && Exceptions.ErrorOccurred())
{
goto convert_error;
}
if (num > Int16.MaxValue || num < Int16.MinValue)
{
goto overflow;
}
result = (short)num;
return true;
}
case TypeCode.Int64:
{
if (Runtime.Is32Bit)
{
if (!Runtime.PyLong_Check(value))
{
goto type_error;
}
long? num = Runtime.PyLong_AsLongLong(value);
if (num == -1 && Exceptions.ErrorOccurred())
{
goto convert_error;
}
result = num;
return true;
}
else
{
op = Runtime.PyNumber_Long(value);
if ((op.IsNull() || op.IsNone()) && Exceptions.ErrorOccurred())