gotk4
gotk4 copied to clipboard
Support GWeakRef
There is one particular use case where GWeakRef would be very useful: a weak
reference can be added to a *GdkPixbuf so that it is removed from a cache once
all references to it (that aren't ours) are dropped.
We can do this by having the following API:
type WeakReference struct {
weakRef *C.GWeakRef
}
// Take takes a strong reference from the weak reference. It returns nil if the
// object is already gone.
func (r *WeakReference) Take() Objector
func (obj *Object) AddWeakReference(onFreed func(*WeakReference)) (remove func())
Several notes:
- It is important for
onFreedto be wrapped inside a callback that removes itself from the global registry, since it is called exactly once. The same goes forremove. - The user should never reference
objat all inonFreed. It might be very easy to make this mistake, but doing so will cause the object to never be freed.