123456789_123456789_123456789_123456789_123456789_

Class: FFI::ManagedStruct

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, Struct
Instance Chain:
self, Struct
Inherits: FFI::Struct
Defined in: lib/ffi/managedstruct.rb

Overview

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, ManagedStruct will invoke the class’s release() method during object finalization.

Examples:

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 Attribute Summary

Struct - Inherited

.size

Get struct size.

.size=

set struct size.

Class Method Summary

Struct - Inherited

.alignment, .auto_ptr, .by_ref, .by_value, .in, .layout, .members,
.offset_of

Get the offset of a field.

.offsets

Get an array of tuples (field name, offset of the field).

.out, .ptr, .val,
.array_layout

Add array spec to builder.

.hash_layout

Add hash spec to builder.

Instance Method Summary

Struct - Inherited

#align

Alias for Struct#alignment.

#alignment,
#clear

Clear the struct content.

#members,
#offset_of

Get the offset of a field.

#offsets

Get an array of tuples (field name, offset of the field).

#size

Get struct size.

#to_ptr

Get Pointer to struct content.

#values

Get array of values from Struct fields.

Constructor Details

.new(pointer) ⇒ ManagedStruct .newManagedStruct

A new instance of ManagedStruct.

Raises:

  • (NoMethodError)
[ GitHub ]

  
# File 'lib/ffi/managedstruct.rb', line 77

def initialize(pointer=nil)
  raise NoMethodError, "release() not implemented for class #{self}" unless self.class.respond_to?(:release, true)
  raise ArgumentError, "Must supply a pointer to memory for the Struct" unless pointer
  super AutoPointer.new(pointer, self.class.method(:release))
end