Class: PyCall::WrapperObjectCache

Inherits:
Object
  • Object
show all
Defined in:
lib/pycall/wrapper_object_cache.rb

Instance Method Summary collapse

Constructor Details

#initialize(*restricted_pytypes) ⇒ WrapperObjectCache

Returns a new instance of WrapperObjectCache.



3
4
5
6
7
8
9
10
11
12
13
14
# File 'lib/pycall/wrapper_object_cache.rb', line 3

def initialize(*restricted_pytypes)
  unless restricted_pytypes.empty?
    restricted_pytypes.each do |pytype|
      next if pytype.kind_of? PyTypePtr
      raise TypeError, "unexpected type of object in the arguments (#{pytype.class} for PyCall::PyTypePtr)"
    end
  end
  @restricted_pytypes = restricted_pytypes
  @wrapper_object_table = {}
  @wrapped_pyptr_table = {}
  @weakref_table = {}
end

Instance Method Details

#check_wrapper_object(wrapper_object) ⇒ Object



41
42
43
44
45
# File 'lib/pycall/wrapper_object_cache.rb', line 41

def check_wrapper_object(wrapper_object)
  unless wrapper_object.kind_of?(PyObjectWrapper)
    raise TypeError, "unexpected wrapper object (expected an object extended by PyObjectWrapper)"
  end
end

#lookup(pyptr) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/pycall/wrapper_object_cache.rb', line 16

def lookup(pyptr)
  # TODO: check pytypeptr type
  unless pyptr.kind_of? PyPtr
    raise TypeError, "unexpected argument type #{pyptr.class} (expected PyCall::PyPtr)"
  end

  unless @restricted_pytypes.empty?
    unless @restricted_pytypes.any? {|pytype| pyptr.kind_of? pytype }
      raise TypeError, "unexpected argument Python type #{pyptr.__ob_type__.__name__} (expected either of them in [#{@restricted_pytypes.map(&:__tp_name__).join(', ')}])"
    end
  end

  wrapper_object_id = @wrapper_object_table[pyptr.__address__]
  if wrapper_object_id
    wrapper_object = ObjectSpace._id2ref(wrapper_object_id) rescue nil
    return wrapper_object if wrapper_object
  end

  wrapper_object = yield(pyptr)
  check_wrapper_object(wrapper_object)
  register_wrapper_object(pyptr, wrapper_object)

  wrapper_object
end

#register_wrapper_object(pyptr, wrapper_object) ⇒ Object



47
48
49
50
51
52
53
# File 'lib/pycall/wrapper_object_cache.rb', line 47

def register_wrapper_object(pyptr, wrapper_object)
  @wrapper_object_table[pyptr.__address__] = wrapper_object.__id__
  @wrapped_pyptr_table[wrapper_object.__id__] = pyptr.__address__
  ObjectSpace.define_finalizer(wrapper_object, &method(:unregister_wrapper_object))
  # TODO: weakref
  self
end

#unregister_wrapper_object(wrapper_object_id) ⇒ Object



55
56
57
58
59
# File 'lib/pycall/wrapper_object_cache.rb', line 55

def unregister_wrapper_object(wrapper_object_id)
  pyptr_addr = @wrapped_pyptr_table.delete(wrapper_object_id)
  @wrapper_object_table.delete(pyptr_addr) if pyptr_addr
  self
end