diamondburned/gotk4

Support GWeakRef

diamondburned opened this issue · 0 comments

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 onFreed to be wrapped inside a callback that removes
    itself from the global registry, since it is called exactly once. The same
    goes for remove.
  • The user should never reference obj at all in onFreed. It might be
    very easy to make this mistake, but doing so will cause the object to never be
    freed.