C Binding: How to call the memory release function when being finalized by GC

Hi, is there anything like Ruby-FFI’s FFI::ManagedStruct in Crystal?

module MyLibrary
  class SomeObject < FFI::ManagedStruct
    layout :next,  :pointer,
           :name,  :string,
           :value, :double,

    def self.release(ptr)
      MyLibrary.free_object(ptr)
    end
  end
end

It seems that the function to release memory is called by define_finalizer.

define_finalizer

You would want to define a finalize - Crystal method.

1 Like

Thanks. This seems to work well.
I’ll try to find an actual use case on Github.

As Blacksmoke16 taught me, I implemented the finalizer method in the class that holds the C struct. This has significantly reduced memory usage. Unlike Ruby-FFI, crystal language structs declared in Lib are not classes, so you can’t implement finalizer methods directly.

The question here is whether creating a class that holds the struct and registering a function that frees memory in the finalizer method of that class is the preferred pattern of memory management.

It’s a common pattern in Ruby-FFI. But there may be a different way to do it in Crystal language. is there a more common pattern in Crystal language?

Or, if anyone has a recommended project that I can refer to when implementing C binding, I would appreciate it.

Thank you.

Using a class and finalize is the preferred and only way to do it.

2 Likes