Bip901
Bip901

Reputation: 808

Memory management of Godot (C++) objects in C#

Introduction

Since the Godot.Collections objects are wrappers around C++ objects, we have to memory-manage them manually. For example, in the following test:

public override void _Process(float delta) {
    for (int i = 0; i < 1000; i++)
    {
        new Godot.Collections.Array().Dispose();
    }
}

The memory usage is stable, but omitting the Dispose() call causes the process's memory usage to constantly rise, as expected.

Question

When passing Godot.Collections objects back to native code, who is responsible for freeing them? For example, in the following code:

using (WebRTCPeerConnection peer = new WebRTCPeerConnection())
{
    var dict = new Godot.Collections.Dictionary();
    peer.Initialize(dict);
    dict.Dispose(); // Should I?
   // do something with peer
}

Should I dispose dict, or does the disposal of the peer suffice?

Another, more common example, is the binds array when connecting to signals:

button.Connect("pressed", this, "OnButtonPressed", new Godot.Collections.Array(123));

Should I dispose of the array immediately after the call?

If the native callee owns the memory, disposing it myself would cause a use-after-free, but if the C# script owns the memory and doesn't dispose, memory is leaked.

I suspect both the C# script and the native call increment the reference count, thus both need to be disposed in order for the memory to be freed, but I couldn't find information about it in the docs.

Upvotes: 0

Views: 63

Answers (0)

Related Questions