module FFI

def self.create_invoker(lib, name, args, ret_type, options = { :convention => :default })

def self.create_invoker(lib, name, args, ret_type, options = { :convention => :default })
  # Current artificial limitation based on JRuby::FFI limit
  raise SignatureError, 'FFI functions may take max 32 arguments!' if args.size > 32
  # Open the library if needed
  library = if lib.kind_of?(DynamicLibrary)
    lib
  elsif lib.kind_of?(String)
    # Allow FFI.create_invoker to be  called with a library name
    DynamicLibrary.open(FFI.map_library_name(lib), DynamicLibrary::RTLD_LAZY)
  elsif lib.nil?
    FFI::Library::DEFAULT
  else
    raise LoadError, "Invalid library '#{lib}'"
  end
  function = library.find_function(name)
  raise NotFoundError.new(name, library.name) unless function
  args = args.map {|e| find_type(e) }
  invoker = if args.length > 0 && args[args.length - 1] == FFI::NativeType::VARARGS
    FFI::VariadicInvoker.new(function, args, find_type(ret_type), options)
  else
    FFI::Function.new(find_type(ret_type), args, function, options)
  end
  raise NotFoundError.new(name, library.name) unless invoker
  return invoker
end