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.
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.