Subject:
Re: [ruby-ffi] Re: c++ examples
From:
Wayne Meissner
Date:
12/9/09 2:54 PM
To:
ruby-ffi@googlegroups.com

2009/12/10 rogerdpack <rogerpack2005@gmail.com>:
>> I do not recommend this at all. Using finalizers to release external resources is a very easy way to cause memory leaks and latent bugs.
>
> Anybody know if collection at finalize time what the following code
> (from the tutorial) does by default?

When the SomeObject instance is garbage collected, the 'release'
method is called on the class, passing in the pointer used as the
memory for the struct.

The problem, is, that in a garbage collected environment, garbage
collection is not a deterministic event.

i.e.  it doesn't happen the instant the last reference to the
SomeObject instance goes out of scope, it may be quite some time
later, or never, if there is no memory pressure from ruby objects
allocations.

You can use finalizers as a last-resort cleanup mechanism, but you
also want to have a mechanism to cleanup/dispose the underlying native
object explicitly during normal operation.

>
> module MyLibrary
>  class SomeObject < FFI::ManagedStruct
>    layout :next,  :pointer,
>           :name,  :string,
>           :value, :double,
>
>    def self.release(ptr)
>      MyLibrary.free_object(ptr)
>    end
>  end
> end
> Thanks.
> -r
>