Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 2ac5f4e

Browse files
authored
Merge pull request #1484 from losttech/Mini/NoCrashWhenSequenceLengthUndefined
Fixed crash in ToArray when sequence explicitly denies __len__
2 parents ea61b03 + b52823b commit 2ac5f4e

File tree

1 file changed

+16
-7
lines changed

1 file changed

+16
-7
lines changed

src/runtime/converter.cs

+16-7
Original file line numberDiff line numberDiff line change
@@ -882,17 +882,26 @@ 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+
if (len <= int.MaxValue)
892+
{
893+
constructorArgs = new object[] { (int)len };
894+
}
895+
}
896+
else
897+
{
898+
// for the sequences, that explicitly deny calling __len__()
899+
Exceptions.Clear();
900+
}
895901
}
902+
// CreateInstance can throw even if MakeGenericType succeeded.
903+
// See https://docs.microsoft.com/en-us/dotnet/api/system.activator.createinstance#System_Activator_CreateInstance_System_Type_
904+
list = (IList)Activator.CreateInstance(constructedListType, args: constructorArgs);
896905
}
897906
catch (Exception e)
898907
{

0 commit comments

Comments
 (0)