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.