Class: NiceFFI::TypedPointer

Inherits:
Object
  • Object
show all
Defined in:
lib/nice-ffi/typedpointer.rb

Overview

TypedPointer represents a :pointer (FFI type) that is a specific struct type. You can use TypedPointer( SomeStructClass ) instead of :pointer in these situations:

  • As the type for NiceFFI::Struct#layout to create type-smart accessors.

  • As the return type for NiceFFI::Library#attach_function to wrap the returned pointer.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type, options = {}) ⇒ TypedPointer

Create a new TypedPointer whose type is the given struct class.

type must be a class (not an instance) which is a descendent of FFI::Struct (or is FFI::Struct itself).

options must be a Hash of zero or more options. The current meaningful options are:

  • :autorelease - If false, instances of NiceStruct and OpaqueStruct (and subclasses) created via this TypedPointer will be passed => false to disable automatic memory management. Use this for return values of functions that should not be autoreleased.



55
56
57
58
59
60
61
62
# File 'lib/nice-ffi/typedpointer.rb', line 55

def initialize( type, options={} )
  # unless type.is_a? Class and type.ancestors.include? FFI::Struct
  #   raise TypeError, "#{self.class} only wraps FFI::Struct and subclasses."
  # end
  @type = type
  options = {:autorelease => true}.merge!( options )
  @autorelease = options[:autorelease]
end

Instance Attribute Details

#typeObject (readonly)

Returns the value of attribute type.



64
65
66
# File 'lib/nice-ffi/typedpointer.rb', line 64

def type
  @type
end

Instance Method Details

#to_sObject Also known as: inspect



90
91
92
# File 'lib/nice-ffi/typedpointer.rb', line 90

def to_s
  "#<#{self.class}[ #{@type} ]>"
end

#unwrap(struct) ⇒ Object

Unwrap (i.e. extract the pointer) from a struct of this type.



82
83
84
85
86
87
# File 'lib/nice-ffi/typedpointer.rb', line 82

def unwrap( struct )
  unless struct.is_a? @type
    raise TypeError, "#{self.class}[ #{@type} ] cannot unwrap #{struct.type}"
  end
  struct.to_ptr
end

#wrap(pointer) ⇒ Object

Wrap a FFI::Pointer in a new struct of this type.



68
69
70
71
72
73
74
75
76
77
78
# File 'lib/nice-ffi/typedpointer.rb', line 68

def wrap( pointer )
  unless pointer.is_a? FFI::Pointer
    raise TypeError, "#{self.class}[ #{@type} ] cannot wrap #{pointer.type}"
  end

  if @type.included_modules.include?( NiceFFI::AutoRelease )
    @type.new( pointer, :autorelease => @autorelease )
  else
    @type.new( pointer )
  end
end