From 5b3b9cd63bd3cc57851799e0912b1ed770598434 Mon Sep 17 00:00:00 2001 From: Ignacio Etcheverry Date: Mon, 15 Mar 2021 07:08:06 +0100 Subject: [PATCH] C#: Fix disconnecting event signals twice `disconnect_event_signals` can be called twice (when managed instance is disposed and from the ScriptInstance destructor). --- modules/mono/csharp_script.cpp | 20 +++++++++----------- modules/mono/csharp_script.h | 2 ++ 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/modules/mono/csharp_script.cpp b/modules/mono/csharp_script.cpp index 610cecae7c42..43f57a7caaf7 100644 --- a/modules/mono/csharp_script.cpp +++ b/modules/mono/csharp_script.cpp @@ -2018,22 +2018,20 @@ void CSharpInstance::connect_event_signals() { // TODO: Use pooling for ManagedCallable instances. auto event_signal_callable = memnew(EventSignalCallable(owner, &event_signal)); - owner->connect(signal_name, Callable(event_signal_callable)); + Callable callable(event_signal_callable); + connected_event_signals.push_back(callable); + owner->connect(signal_name, callable); } } void CSharpInstance::disconnect_event_signals() { - for (const Map::Element *E = script->event_signals.front(); E; E = E->next()) { - const CSharpScript::EventSignal &event_signal = E->value(); - - StringName signal_name = event_signal.field->get_name(); - - // TODO: It would be great if we could store this EventSignalCallable on the stack. - // The problem is that Callable memdeletes it when it's destructed... - auto event_signal_callable = memnew(EventSignalCallable(owner, &event_signal)); - - owner->disconnect(signal_name, Callable(event_signal_callable)); + for (const List::Element *E = connected_event_signals.front(); E; E = E->next()) { + const Callable &callable = E->get(); + auto event_signal_callable = static_cast(callable.get_custom()); + owner->disconnect(event_signal_callable->get_signal(), callable); } + + connected_event_signals.clear(); } void CSharpInstance::refcount_incremented() { diff --git a/modules/mono/csharp_script.h b/modules/mono/csharp_script.h index 40f7ed4552d4..dd93a86d7a3d 100644 --- a/modules/mono/csharp_script.h +++ b/modules/mono/csharp_script.h @@ -271,6 +271,8 @@ class CSharpInstance : public ScriptInstance { Ref script; MonoGCHandleData gchandle; + List connected_event_signals; + bool _reference_owner_unsafe(); /*