@@ -28,18 +28,18 @@ public bool TryDecode<T>(PyObject pyObj, out T value)
2828 return false ;
2929 }
3030
31- using ( var pyList = PyList . AsList ( pyObj ) )
31+ if ( typeof ( T ) . IsGenericType )
3232 {
33- if ( typeof ( T ) . IsGenericType )
33+ using ( var pyList = PyList . AsList ( pyObj ) )
3434 {
3535 value = pyList . ToList < T > ( ) ;
3636 }
37- else
38- {
39- value = ( T ) pyList . ToList ( ) ;
40- }
4137 return true ;
4238 }
39+
40+ var converted = ConvertToArrayList ( pyObj ) ;
41+ value = ( T ) converted ;
42+ return true ;
4343 }
4444
4545 public PyObject TryEncode ( object value )
@@ -57,5 +57,53 @@ bool IPyObjectDecoder.CanDecode(PyType objectType, Type targetType)
5757 }
5858 return decodableTypes . IndexOf ( targetType ) >= 0 ;
5959 }
60+
61+ private static IList ConvertToArrayList ( PyObject pyObj )
62+ {
63+ using var pyList = PyList . AsList ( pyObj ) ;
64+ var result = new ArrayList ( ) ;
65+ foreach ( PyObject item in pyList )
66+ {
67+ using ( item )
68+ {
69+ result . Add ( ConvertItem ( item ) ) ;
70+ }
71+ }
72+ return result ;
73+ }
74+
75+ private static object ConvertItem ( PyObject item )
76+ {
77+ if ( TryGetClrObject ( item , out var clrObject ) )
78+ {
79+ return clrObject ;
80+ }
81+
82+ if ( PyString . IsStringType ( item ) )
83+ {
84+ return item . AsManagedObject ( typeof ( string ) ) ;
85+ }
86+
87+ if ( PyList . IsListType ( item ) || PyTuple . IsTupleType ( item ) )
88+ {
89+ return ConvertToArrayList ( item ) ;
90+ }
91+
92+ return item . AsManagedObject ( typeof ( object ) ) ;
93+ }
94+
95+ private static bool TryGetClrObject ( PyObject pyObj , out object clrObject )
96+ {
97+ try
98+ {
99+ clrObject = pyObj . GetManagedObject ( ) ;
100+ return clrObject != null ;
101+ }
102+ catch
103+ {
104+ clrObject = null ;
105+ return false ;
106+ }
107+ }
60108 }
61109}
0 commit comments