Sha256: 37ff5ec08897735b121b27c9313dc8b851b7629bf742fbe8b2d2cfb6d3dce1e7

Contents?: true

Size: 1.41 KB

Versions: 8

Compression:

Stored size: 1.41 KB

Contents

require 'ffi-gobject/closure'

module GObject
  # Encapsulates Ruby blocks as GObject Closures.
  class RubyClosure < Closure
    # @api private
    BLOCK_STORE = {}

    # Extend the standard +GObject::Closure+ layout with a field block_id to store
    # the object_id of the associated block.
    #
    # @api private
    class Struct < FFI::Struct
      layout :parent, Closure::Struct, 0,
             :block_id, :int64
    end

    def initialize(&block)
      raise ArgumentError unless block_given?

      initialize_simple(self.class::Struct.size, nil)
      self.block = block
      set_marshal proc { |*args| self.class.marshaller(*args) }
    end

    # @api private
    def self.marshaller(closure, return_value, param_values, _invocation_hint,
                        _marshal_data)
      # TODO: Improve by registering RubyClosure as a GObject type
      rclosure = wrap(closure.to_ptr)
      param_values ||= []

      args = param_values.map(&:get_value)

      result = rclosure.invoke_block(*args)

      return_value.set_value(result) if return_value
    end

    # @api private
    # TODO: Re-structure so invoke_block can become a private method
    def invoke_block(*args)
      block.call(*args)
    end

    private

    # @api private
    def block=(block)
      id = block.object_id
      BLOCK_STORE[id] = block
      @struct[:block_id] = id
    end

    def block
      BLOCK_STORE[@struct[:block_id]]
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
gir_ffi-0.9.2 lib/ffi-gobject/ruby_closure.rb
gir_ffi-0.9.1 lib/ffi-gobject/ruby_closure.rb
gir_ffi-0.9.0 lib/ffi-gobject/ruby_closure.rb
gir_ffi-0.8.6 lib/ffi-gobject/ruby_closure.rb
gir_ffi-0.8.5 lib/ffi-gobject/ruby_closure.rb
gir_ffi-0.8.4 lib/ffi-gobject/ruby_closure.rb
gir_ffi-0.8.3 lib/ffi-gobject/ruby_closure.rb
gir_ffi-0.8.2 lib/ffi-gobject/ruby_closure.rb