Module: NiceFFI::AutoRelease

Included in:
OpaqueStruct, Struct
Defined in:
lib/nice-ffi/autorelease.rb

Overview

A mixin module to provide automatic memory management for C structs.

Class Method Summary collapse

Class Method Details

.included(klass) ⇒ Object

Sets up the class when this module is included. Adds the class

methods and defines class instance variables.


44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# 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