From afa5932ddbbed22c6a7ef9bc1652adea32c4848f Mon Sep 17 00:00:00 2001 From: zach Date: Fri, 3 Nov 2023 09:56:09 -0700 Subject: [PATCH] fix: ensure extism functions are freed (#17) Fixes #12 using a similar approach to how plugins are cleaned up using `ObjectSpace.define_finalizer` --- lib/extism.rb | 10 ++++++++++ lib/extism/wasm.rb | 3 +++ 2 files changed, 13 insertions(+) diff --git a/lib/extism.rb b/lib/extism.rb index 0852069..77f5927 100644 --- a/lib/extism.rb +++ b/lib/extism.rb @@ -35,6 +35,16 @@ def self.set_log_file(name, level = nil) end } + + $FUNCTIONS = {} + $FREE_FUNCTION = proc { |ptr| + x = $FUNCTIONS[ptr] + unless x.nil? + LibExtism.extism_function_free(x[:function]) + $FUNCTIONS.delete(ptr) + end + } + # Represents a "block" of memory in Extism. # This memory is in the communication buffer b/w the # guest in the host and technically lives in host memory. diff --git a/lib/extism/wasm.rb b/lib/extism/wasm.rb index 3c7013a..1a68f7d 100644 --- a/lib/extism/wasm.rb +++ b/lib/extism/wasm.rb @@ -93,6 +93,9 @@ def pointer returns = LibExtism.from_int_array(@returns) @_pointer = LibExtism.extism_function_new(@name, args, @params.length, returns, @returns.length, c_func, free, nil) + $FUNCTIONS[object_id] = { function: @_pointer} + ObjectSpace.define_finalizer(self, $FREE_FUNCTION) + return @_pointer end def c_func