Method: FFI::AutoPointer#initialize

Defined in:
lib/ffi/autopointer.rb

#initialize(pointer, method) ⇒ self #initialize(pointer, proc) ⇒ self #initialize(pointer) ⇒ self

Note:

The safest, and therefore preferred, calling idiom is to pass a Method as the second parameter. Example usage:

class PointerHelper
  def self.release(pointer)
    ...
  end
end

p = AutoPointer.new(other_pointer, PointerHelper.method(:release))

The above code will cause PointerHelper#release to be invoked at GC time.

Note:

The last calling idiom (only one parameter) is generally only going to be useful if you subclass FFI::AutoPointer, and override #release, which by default does nothing.

Returns a new instance of AutoPointer.

Overloads:

  • #initialize(pointer, method) ⇒ self

    The passed Method will be invoked at GC time.

    Parameters:

    • pointer (Pointer)
    • method (Method)
  • #initialize(pointer, proc) ⇒ self
    Note:

    WARNING: passing a proc may cause your pointer to never be GC’d, unless you’re careful to avoid trapping a reference to the pointer in the proc. See the test specs for examples.

    The passed Proc will be invoked at GC time (SEE WARNING BELOW!)

    Parameters:

  • #initialize(pointer) ⇒ self

    The pointer’s release() class method will be invoked at GC time.

    Parameters:

Raises:

  • (TypeError)


70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/ffi/autopointer.rb', line 70

def initialize(ptr, proc=nil)
  raise TypeError, "Invalid pointer" if ptr.nil? || !ptr.kind_of?(Pointer) ||
      ptr.kind_of?(MemoryPointer) || ptr.kind_of?(AutoPointer)
  super(ptr.type_size, ptr)

  @releaser = if proc
                if not proc.respond_to?(:call)
                  raise RuntimeError.new("proc must be callable")
                end
                Releaser.new(ptr, proc)

              else
                if not self.class.respond_to?(:release, true)
                  raise RuntimeError.new("no release method defined")
                end
                Releaser.new(ptr, self.class.method(:release))
              end

  ObjectSpace.define_finalizer(self, @releaser)
  self
end