module NiceFFI::AutoRelease
A mixin module to provide automatic memory management for C structs.
Public Class Methods
included( klass )
click to toggle source
Sets up the class when this module is included. Adds the class methods and defines class instance variables.
# File lib/nice-ffi/autorelease.rb, line 44 def self.included( klass ) class << klass # Increment the reference count for this address. def _incr_refcount( address ) @ptr_mutex ||= Mutex.new @ptr_mutex.synchronize { @ptr_refcounts ||= Hash.new(0) @ptr_refcounts[address] += 1 } return nil end # Decrement the counter for this pointer's address, and free # the memory if the reference count falls below 1. # def _release( pointer ) @ptr_mutex ||= Mutex.new @ptr_mutex.synchronize { _decr_refcount(pointer.address) if( @ptr_refcounts[pointer.address] < 1 ) release( pointer ) end } end private # Decrement the reference count for this address. If the count falls # below 1, the address is removed from Hash altogether. # # Note: this method does not have a Mutex lock by itself, but you # should use a lock in any methods that call it. # def _decr_refcount( address ) @ptr_refcounts ||= Hash.new(0) @ptr_refcounts[address] -= 1 if( @ptr_refcounts[address] < 1 ) @ptr_refcounts.delete(address) end end end end
Private Instance Methods
_make_autopointer( ptr, autorelease=true )
click to toggle source
# File lib/nice-ffi/autorelease.rb, line 93 def _make_autopointer( ptr, autorelease=true ) if( autorelease and self.class.respond_to?(:release) and ptr.is_a?(FFI::Pointer) and not ptr.is_a?(FFI::MemoryPointer) and not ptr.is_a?(FFI::Buffer) ) # Increment the reference count for this pointer address self.class._incr_refcount( ptr.address ) # Wrap in an AutoPointer to call self.class._release when it's GC'd. return FFI::AutoPointer.new( ptr, self.class.method(:_release) ) else return ptr end end