8000 fixed crash in ToArray when sequence explicitly denies __len__ · losttech/pythonnet@8e1d4db · GitHub
[go: up one dir, main page]

Skip to content

Commit 8e1d4db

Browse files
committed
fixed crash in ToArray when sequence explicitly denies __len__
1 parent d55a914 commit 8e1d4db

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

src/runtime/converter.cs

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -761,6 +761,11 @@ private static bool ToArray(IntPtr value, Type obType, out object result, bool s
761761

762762
bool IsSeqObj = Runtime.PySequence_Check(value);
763763
var len = IsSeqObj ? Runtime.PySequence_Size(value) : -1;
764+
if (IsSeqObj && len < 0)
765+
{
766+
// for the sequences, that explicitly deny calling __len__()
767+
Exceptions.Clear();
768+
}
764769

765770
var IterObject = Runtime.PyObject_GetIter(new BorrowedReference(value));
766771

@@ -776,8 +781,9 @@ private static bool ToArray(IntPtr value, Type obType, out object result, bool s
776781

777782
var listType = typeof(List<>);
778783
var constructedListType = listType.MakeGenericType(elementType);
779-
IList list = IsSeqObj ? (IList) Activator.CreateInstance(constructedListType, new Object[] {(int) len}) :
780-
(IList) Activator.CreateInstance(constructedListType);
784+
IList list = IsSeqObj && len > 0
785+
? (IList) Activator.CreateInstance(constructedListType, args: (int)len)
786+
: (IList) Activator.CreateInstance(constructedListType);
781787
NewReference item;
782788

783789
while (!(item = Runtime.PyIter_Next(IterObject)).IsNull())

0 commit comments

Comments
 (0)
0