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

Skip to content

Commit a6f27ab

Browse files
committed
fix memory access error when iteration breaks
in the middle of the list before reaching end.
1 parent 8e8c3f3 commit a6f27ab

File tree

1 file changed

+41
-37
lines changed

1 file changed

+41
-37
lines changed
Lines changed: 41 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,46 @@
1-
using System;
2-
using System.Collections.Generic;
3-
using System.Collections;
4-
5-
namespace Python.Runtime.CollectionWrappers
6-
{
7-
internal class IterableWrapper<T> : IEnumerable<T>
8-
{
9-
protected readonly PyObject pyObject;
10-
11-
public IterableWrapper(PyObject pyObj)
12-
{
13-
if (pyObj == null)
14-
throw new ArgumentNullException();
15-
pyObject = new PyObject(pyObj.Reference);
16-
}
17-
18-
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
19-
20-
public IEnumerator<T> GetEnumerator()
21-
{
22-
PyIter iterObject;
23-
using (Py.GIL())
24-
{
25-
iterObject = PyIter.GetIter(pyObject);
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Collections;
4+
5+
namespace Python.Runtime.CollectionWrappers
6+
{
7+
internal class IterableWrapper<T> : IEnumerable<T>
8+
{
9+
protected readonly PyObject pyObject;
10+
11+
public IterableWrapper(PyObject pyObj)
12+
{
13+
if (pyObj == null)
14+
throw new ArgumentNullException();
15+
pyObject = new PyObject(pyObj.Reference);
16+
}
17+
18+
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
19+
20+
public IEnumerator<T> GetEnumerator()
21+
{
22+
PyIter iterObject;
23+
using (Py.GIL())
24+
{
25+
iterObject = PyIter.GetIter(pyObject);
2626
}
27-
28-
using var _ = iterObject;
29-
while (true)
27+
try
3028
{
31-
using var GIL = Py.GIL();
32-
33-
if (!iterObject.MoveNext())
29+
while (true)
3430
{
35-
iterObject.Dispose();
36-
break;
31+
using var _ = Py.GIL();
32+
if (!iterObject.MoveNext())
33+
{
34+
break;
35+
}
36+
yield return iterObject.Current.As<T>()!;
3737
}
38-
yield return iterObject.Current.As<T>()!;
3938
}
40-
}
41-
}
42-
}
39+
finally
40+
{
41+
using var _ = Py.GIL();
42+
iterObject.Dispose();
43+
}
44+
}
45+
}
46+
}

0 commit comments

Comments
 (0)