Skip to content

Commit e974da4

Browse files
diamondburnedjgillich
authored andcommitted
Fix floating reference handling in intern
Fixes diamondburned#126
1 parent 92b38b3 commit e974da4

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

pkg/core/intern/intern.go

+19-4
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,10 @@ func objInfo(obj unsafe.Pointer) string {
123123
return fmt.Sprintf("%p (%s):", obj, C.GoString(C.gotk4_object_type_name(C.gpointer(obj))))
124124
}
125125

126+
func objRefCount(obj unsafe.Pointer) int {
127+
return int(C.g_atomic_int_get((*C.gint)(unsafe.Pointer(&(*C.GObject)(obj).ref_count))))
128+
}
129+
126130
// newBox creates a zero-value instance of Box.
127131
func newBox(obj unsafe.Pointer) *Box {
128132
box := &Box{}
@@ -211,8 +215,7 @@ func Get(gobject unsafe.Pointer, take bool) *Box {
211215

212216
if toggleRefs != nil {
213217
toggleRefs.Println(objInfo(gobject),
214-
"Get: will introduce new box, current ref =",
215-
C.g_atomic_int_get((*C.gint)(unsafe.Pointer(&(*C.GObject)(gobject).ref_count))))
218+
"Get: will introduce new box, current ref =", objRefCount(gobject))
216219
}
217220

218221
shared.mu.Unlock()
@@ -225,20 +228,32 @@ func Get(gobject unsafe.Pointer, take bool) *Box {
225228
// We should already have a strong reference. Sink the object in case. This
226229
// will force the reference to be truly strong.
227230
if C.g_object_is_floating(C.gpointer(gobject)) != C.FALSE {
231+
// First, we need to ref_sink the object to convert the floating
232+
// reference to a strong reference.
228233
C.g_object_ref_sink(C.gpointer(gobject))
234+
// Then, we need to unref it to balance the ref_sink.
235+
C.g_object_unref(C.gpointer(gobject))
236+
237+
if toggleRefs != nil {
238+
toggleRefs.Println(objInfo(gobject),
239+
"Get: ref_sink'd the object, current ref =", objRefCount(gobject))
240+
}
229241
}
230242

231243
// If we're "not taking," then we can assume our ownership over the object,
232244
// meaning the strong reference is now ours. That means we need to replace
233245
// it, not add.
234246
if !take {
247+
if toggleRefs != nil {
248+
toggleRefs.Println(objInfo(gobject),
249+
"Get: not taking, so unrefing the object, current ref =", objRefCount(gobject))
250+
}
235251
C.g_object_unref(C.gpointer(gobject))
236252
}
237253

238254
if toggleRefs != nil {
239255
toggleRefs.Println(objInfo(gobject),
240-
"Get: introduced new box, current ref =",
241-
C.g_atomic_int_get((*C.gint)(unsafe.Pointer(&(*C.GObject)(gobject).ref_count))))
256+
"Get: introduced new box, current ref =", objRefCount(gobject))
242257
}
243258

244259
// Undo the initial ref_sink.

0 commit comments

Comments
 (0)