Method: LIBUSB::Context#initialize
- Defined in:
- lib/libusb/context.rb
#initialize(options = {}) ⇒ Context
Initialize libusb context.
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 |
# File 'lib/libusb/context.rb', line 105 def initialize(={}) m = FFI::MemoryPointer.new :pointer if .empty? res = Call.libusb_init(m) LIBUSB.raise_error res, "in libusb_init" if res!=0 else raise ArgumentError, "options require libusb-1.0.27+" unless Call.respond_to?(:libusb_init_context) i_opts = .size p_opts = FFI::MemoryPointer.new(Call::InitOption, i_opts) .each_with_index do |(k, v), i| opt = Call::InitOption.new(p_opts + i * Call::InitOption.size) opt[:option] = k ffitype, ffival = LIBUSB.send(:option_args_to_ffi, k, Array(v), self) case ffitype when NilClass then nil when :libusb_log_level then opt[:value][:ival] = ffival when :libusb_log_cb then opt[:value][:log_cbval] = ffival else raise ArgumentError, "internal error: unexpected ffitype: #{ffitype.inspect}" end end res = Call.libusb_init_context(m, p_opts, i_opts) LIBUSB.raise_error res, "in libusb_init_context" if res!=0 end @ctx = m.read_pointer @on_pollfd_added = nil @on_pollfd_removed = nil @hotplug_callbacks = {} def @ctx.free_context(id) @free_context = true if @refs == 0 # puts "final libusb_exit #{to_i} #{id} #{caller[0]}" if id # Is Context is about to be garbage collected? # In GC mode there's no way to call the registered collbacks, since they are GC'ed as well. # So disable callbacks now. if Call.respond_to?(:libusb_set_log_cb) Call.libusb_set_log_cb(self, nil, LOG_CB_CONTEXT) end Call.libusb_set_pollfd_notifiers(self, nil, nil, nil) end Call.libusb_exit(self) @refs = nil end end def @ctx.ref_context @refs += 1 # puts "ref_context #{to_i} #{@refs} #{caller[1]}" self end def @ctx.unref_context @refs -= 1 # puts "unref_context #{to_i} #{@refs}" raise "more unref_context than ref_context" if @refs < 0 free_context(true) if @refs == 0 && @free_context self end def @ctx.setref_context @refs = 0 @free_context = false end def @ctx.refs @refs end @ctx.setref_context ObjectSpace.define_finalizer(self, @ctx.method(:free_context)) end |