Sha256: d85986d608dd01df995a715ec4262c25b21cf77b3f9cd764f459645d8d71a9ad

Contents?: true

Size: 1.68 KB

Versions: 33

Compression:

Stored size: 1.68 KB

Contents

module FFI
  #
  #  FFI::ManagedStruct allows custom garbage-collection of your FFI::Structs.
  #
  #  The typical use case would be when interacting with a library
  #  that has a nontrivial memory management design, such as a linked
  #  list or a binary tree.
  #
  #  When the Struct instance is garbage collected, FFI::ManagedStruct will
  #  invoke the class's release() method during object finalization.
  #
  #  Example usage:
  #    module MyLibrary
  #      ffi_lib "libmylibrary"
  #      attach_function :new_dlist, [], :pointer
  #      attach_function :destroy_dlist, [:pointer], :void
  #    end
  #
  #    class DoublyLinkedList < FFI::ManagedStruct
  #      @@@
  #      struct do |s|
  #        s.name 'struct dlist'
  #        s.include 'dlist.h'
  #        s.field :head, :pointer
  #        s.field :tail, :pointer
  #      end
  #      @@@
  #
  #      def self.release ptr
  #        MyLibrary.destroy_dlist(ptr)
  #      end
  #    end
  #
  #    begin
  #      ptr = DoublyLinkedList.new(MyLibrary.new_dlist)
  #      #  do something with the list
  #    end
  #    # struct is out of scope, and will be GC'd using DoublyLinkedList#release
  #
  #
  class ManagedStruct < FFI::Struct

    # call-seq:
    #   ManagedStruct.new(pointer)
    #   ManagedStruct.new
    #
    # When passed a pointer, create a new ManagedStruct which will invoke the class method release() on 
    def initialize(pointer=nil)
      raise NoMethodError, "release() not implemented for class #{self}" unless self.class.respond_to? :release
      raise ArgumentError, "Must supply a pointer to memory for the Struct" unless pointer
      super FFI::AutoPointer.new(pointer, self.class.method(:release))
    end

  end
end

Version data entries

33 entries across 33 versions & 5 rubygems

Version Path
ffi-ffi-0.5.0 lib/ffi/managedstruct.rb
remogatto-ffi-0.5.0 lib/ffi/managedstruct.rb
ffi-0.6.4 lib/ffi/managedstruct.rb
resque-pool-0.3.0 vendor/bundle/ruby/1.8/gems/ffi-0.6.3/lib/ffi/managedstruct.rb
resque-pool-0.3.0.beta.2 vendor/bundle/ruby/1.8/gems/ffi-0.6.3/lib/ffi/managedstruct.rb
ffi-0.6.3-x86-mingw32 lib/ffi/managedstruct.rb
ffi-0.6.3-x86-mswin32 lib/ffi/managedstruct.rb
ffi-0.6.3 lib/ffi/managedstruct.rb
ffi-0.6.2 lib/ffi/managedstruct.rb
ffi-0.6.1 lib/ffi/managedstruct.rb
ffi-0.6.0 lib/ffi/managedstruct.rb
ffi-0.5.4-x86-mswin32 lib/ffi/managedstruct.rb
ffi-0.5.4-x86-mingw32 lib/ffi/managedstruct.rb
ffi-0.5.4 lib/ffi/managedstruct.rb
ffi-0.5.3-x86-mswin32 lib/ffi/managedstruct.rb
ffi-0.5.3 lib/ffi/managedstruct.rb
ffi-0.5.3-x86-mingw32 lib/ffi/managedstruct.rb
minilab-1.1.0-x86-mswin32-60 vendor/ffi-0.4.0-x86-mswin32/lib/ffi/managedstruct.rb
ffi-0.5.1-x86-mswin32 lib/ffi/managedstruct.rb
ffi-0.5.1 lib/ffi/managedstruct.rb