Skip to content

Commit f02f565

Browse files
committed
fixed crash in ToArray when sequence explicitly denies __len__
port of 8e1d4db
1 parent ea61b03 commit f02f565

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

src/runtime/converter.cs

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -882,17 +882,23 @@ private static bool ToArray(IntPtr value, Type obType, out object result, bool s
882882
// See https://docs.microsoft.com/en-us/dotnet/api/system.type.makegenerictype#System_Type_MakeGenericType_System_Type
883883
var constructedListType = typeof(List<>).MakeGenericType(elementType);
884884
bool IsSeqObj = Runtime.PySequence_Check(value);
885+
object[] constructorArgs = Array.Empty<object>();
885886
if (IsSeqObj)
886887
{
887888
var len = Runtime.PySequence_Size(value);
888-
list = (IList)Activator.CreateInstance(constructedListType, new Object[] { (int)len });
889-
}
890-
else
891-
{
892-
// CreateInstance can throw even if MakeGenericType succeeded.
893-
// See https://docs.microsoft.com/en-us/dotnet/api/system.activator.createinstance#System_Activator_CreateInstance_System_Type_
894-
list = (IList)Activator.CreateInstance(constructedListType);
889+
if (len >= 0)
890+
{
891+
constructorArgs = new object[] { len };
892+
}
893+
else
894+
{
895+
// for the sequences, that explicitly deny calling __len__()
896+
Exceptions.Clear();
897+
}
895898
}
899+
// CreateInstance can throw even if MakeGenericType succeeded.
900+
// See https://docs.microsoft.com/en-us/dotnet/api/system.activator.createinstance#System_Activator_CreateInstance_System_Type_
901+
list = (IList)Activator.CreateInstance(constructedListType, args: constructorArgs);
896902
}
897903
catch (Exception e)
898904
{

0 commit comments

Comments
 (0)