From e3a90fd781fb853c6d80d3c4bf3dac5f773b5e40 Mon Sep 17 00:00:00 2001 From: Virgil Date: Fri, 3 Apr 2026 19:28:24 +0000 Subject: [PATCH] feat(scope): add GC finalizer cleanup for buffers Co-Authored-By: Virgil --- buffer.go | 4 ++++ scope.go | 7 ++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/buffer.go b/buffer.go index a17cbd4..4723a6a 100644 --- a/buffer.go +++ b/buffer.go @@ -42,6 +42,10 @@ func NewBuffer(size int) *Buffer { buffer.pointer = unsafe.Pointer(&buffer.data[0]) } + runtime.SetFinalizer(buffer, func(owned *Buffer) { + owned.Free() + }) + return buffer } diff --git a/scope.go b/scope.go index 6bea065..b36ffba 100644 --- a/scope.go +++ b/scope.go @@ -6,6 +6,7 @@ package cgo import "C" import ( + "runtime" "sync" "sync/atomic" "unsafe" @@ -29,7 +30,11 @@ type Scope struct { // scope := NewScope() // defer scope.FreeAll() func NewScope() *Scope { - return &Scope{} + scope := &Scope{} + runtime.SetFinalizer(scope, func(owned *Scope) { + owned.FreeAll() + }) + return scope } // Buffer allocates a managed buffer and registers it for scope cleanup. -- 2.45.3