From a969f9f9193e7b1e0bd47c8a947c1d33408b9d39 Mon Sep 17 00:00:00 2001 From: Robin Haberkorn Date: Sat, 3 Sep 2016 19:49:35 +0200 Subject: fixed garbage collection of libsndfile handles * an explicit FFI finalizer must be used. * fixes "Too many open files" errors --- sndfile.lua | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/sndfile.lua b/sndfile.lua index 13c952d..8f2a5e7 100644 --- a/sndfile.lua +++ b/sndfile.lua @@ -178,16 +178,11 @@ function sndfile:new(path, mode, samplerate, channels, format) error(ffi.string(lib.sf_strerror(nil))) end - obj.info = info[0] + obj.handle = ffi.gc(obj.handle, lib.sf_close) - -- NOTE: FFI also allows metatables and finalizers - -- to be set on the C-type itself. - setmetatable(obj, { - __index = self, - __gc = sndfile.close - }) + obj.info = info[0] - return obj + return setmetatable(obj, {__index = self}) end function sndfile:seek(frames, whence) @@ -217,7 +212,9 @@ end function sndfile:close() if self.handle then - lib.sf_close(self.handle) + -- NOTE: Finalizer must be removed to avoid a + -- double-close here and later by the garbage collector. + lib.sf_close(ffi.gc(self.handle, nil)) self.handle = nil end end -- cgit v1.2.3