InstanceCache
A singleton object responsible for caching and managing Proxy instances associated with native GObject pointers.
How It Works
Uses toggle references to track Kotlin/Native-to-GObject bindings.
Ensures that each GObject is associated with only one Kotlin instance.
Eliminates the need for manual
g_object_ref()
andg_object_unref()
calls in Kotlin.Uses a global cache of objects, switching between strong and weak references.
Ensures safe disposal when objects are no longer needed.
Instance Cache
Maintains a global map (
references
) of all GObjects used in Kotlin.Each GObject is stored using either a strong or weak reference:
Strong reference: Prevents GC and ensures the instance stays alive.
Weak reference: Allows GC when the object is no longer used.
Toggle References
GObjects are reference-counted. Normally, objects are explicitly g_object_ref()
and g_object_unref()
. However, toggle references automate this:
If the toggle reference becomes the last reference, the cache switches to weak.
If other references appear, the cache switches back to strong.
This prevents memory leaks while ensuring the instance is reusable.
Toggle references are added like this:
g_object_add_toggle_ref(obj, toggle_notify_cb, NULL);
g_object_unref(obj);
Garbage Collection & Cleaners
When an instance is GC'ed, a Cleaner calls
g_object_remove_toggle_ref()
.This reduces the reference count to 0, ensuring safe disposal.
Floating References
Some GObjects (e.g.,
GInitiallyUnowned
) have floating references.Floating references must be "sunk" (
refSink()
) to ensure correct ownership.InstanceCache
automatically sinks floating references.