Class: GirFFI::CallbackBase

Inherits:
Proc
  • Object
show all
Extended by:
FFI::DataConverter, TypeBase
Defined in:
lib/gir_ffi/callback_base.rb

Overview

Base module for callbacks and vfuncs. NOTE: Another option would be to derive this class from FFI::Function, allowing a more natural implementation of from_native, to_native and wrap.

Constant Summary collapse

CALLBACKS =
[]

Class Method Summary collapse

Instance Method Summary collapse

Methods included from TypeBase

gir_ffi_builder, gir_info

Class Method Details

.copy_value_to_pointer(value, pointer) ⇒ Object



70
71
72
# File 'lib/gir_ffi/callback_base.rb', line 70

def self.copy_value_to_pointer value, pointer
  pointer.put_pointer 0, to_native(value, nil)
end

.from(prc) ⇒ Object

Create Callback from a Proc. Makes sure arguments are properly wrapped, and the callback is stored to prevent garbage collection.



44
45
46
47
48
# File 'lib/gir_ffi/callback_base.rb', line 44

def self.from prc
  wrap_in_callback_args_mapper(prc).tap do |cb|
    store_callback cb
  end
end

.from_native(value, _context) ⇒ Object



15
16
17
18
19
# File 'lib/gir_ffi/callback_base.rb', line 15

def self.from_native value, _context
  return nil if !value || value.null?
  FFI::Function.new(gir_ffi_builder.return_ffi_type,
                    gir_ffi_builder.argument_ffi_types, value)
end

.get_value_from_pointer(pointer) ⇒ Object



74
75
76
# File 'lib/gir_ffi/callback_base.rb', line 74

def self.get_value_from_pointer pointer
  from_native pointer.get_pointer(0), nil
end

.native_typeObject



11
12
13
# File 'lib/gir_ffi/callback_base.rb', line 11

def self.native_type
  FFI::Type::POINTER
end

.store_callback(prc) ⇒ Object



38
39
40
# File 'lib/gir_ffi/callback_base.rb', line 38

def self.store_callback prc
  CALLBACKS << prc
end

.to_ffitypeObject



58
59
60
# File 'lib/gir_ffi/callback_base.rb', line 58

def self.to_ffitype
  self
end

.to_native(value, _context) ⇒ Object



21
22
23
24
25
26
27
28
29
30
# File 'lib/gir_ffi/callback_base.rb', line 21

def self.to_native value, _context
  case value
  when CallbackBase
    value.to_native
  when FFI::Function
    value
  else
    nil
  end
end

.wrap(ptr) ⇒ Object



32
33
34
# File 'lib/gir_ffi/callback_base.rb', line 32

def self.wrap ptr
  from_native ptr, nil
end

.wrap_in_callback_args_mapper(prc) ⇒ Object



50
51
52
53
54
55
56
# File 'lib/gir_ffi/callback_base.rb', line 50

def self.wrap_in_callback_args_mapper prc
  return unless prc

  new do |*args|
    call_with_argument_mapping(prc, *args)
  end
end

Instance Method Details

#to_nativeObject



62
63
64
65
66
67
68
# File 'lib/gir_ffi/callback_base.rb', line 62

def to_native
  @to_native ||= begin
                   builder = self.class.gir_ffi_builder
                   FFI::Function.new(builder.return_ffi_type,
                                     builder.argument_ffi_types, self)
                 end
end