Skip to content

Clear weak reference list when an extension type is destroyed #1761

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 10, 2022
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
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