Visitar URL original
Clear weak reference list when an extension type is destroyed by lostmsu · Pull Request #1761 · pythonnet/pythonnet · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
clear weak reference list when an extension type is destroyed
According to official documentation for defining extension types, if they are to support weak references, they must clear weak reference list associated with the instance in tp_clear.

Extension types were missed in #1758 ( 50da522 )
  • Loading branch information
lostmsu committed Apr 9, 2022
commit 7fa3e8e3b5de6e77c9a0e5467952867df953cd37
32 changes: 32 additions & 0 deletions src/embed_tests/ExtensionTypes.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
using System;

using NUnit.Framework;

using Python.Runtime;

namespace Python.EmbeddingTest;

public class ExtensionTypes
{
[OneTimeSetUp]
public void SetUp()
{
PythonEngine.Initialize();
}

[OneTimeTearDown]
public void Dispose()
{
PythonEngine.Shutdown();
}

[Test]
public void WeakrefIsNone_AfterBoundMethodIsGone()
{
using var makeref = Py.Import("weakref").GetAttr("ref");
var boundMethod = new UriBuilder().ToPython().GetAttr(nameof(UriBuilder.GetHashCode));
var weakref = makeref.Invoke(boundMethod);
boundMethod.Dispose();
Assert.IsTrue(weakref.Invoke().IsNone());
}
}
6 changes: 6 additions & 0 deletions src/runtime/Types/ExtensionType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,12 @@ public unsafe static void tp_dealloc(NewReference lastRef)

public static int tp_clear(BorrowedReference ob)
{
var weakrefs = Runtime.PyObject_GetWeakRefList(ob);
if (weakrefs != null)
{
Runtime.PyObject_ClearWeakRefs(ob);
}

if (TryFreeGCHandle(ob))
{
bool deleted = loadedExtensions.Remove(ob.DangerousGetAddress());
Expand Down
6 changes: 6 additions & 0 deletions src/runtime/Types/MetaType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,12 @@ public static NewReference mp_subscript(BorrowedReference tp, BorrowedReference
/// </summary>
public static void tp_dealloc(NewReference lastRef)
{
var weakrefs = Runtime.PyObject_GetWeakRefList(lastRef.Borrow());
if (weakrefs != null)
{
Runtime.PyObject_ClearWeakRefs(lastRef.Borrow());
}

// Fix this when we dont cheat on the handle for subclasses!

var flags = PyType.GetFlags(lastRef.Borrow());
Expand Down