1# -*- ruby -*-
2# for backward compatibility
3warn "Warning:#{caller[0].sub(/:in `.*'\z/, '')}: Win32API is deprecated after Ruby 1.9.1; use dl directly instead" if $VERBOSE
4
5require 'dl'
6
7class Win32API
8  DLL = {}
9  TYPEMAP = {"0" => DL::TYPE_VOID, "S" => DL::TYPE_VOIDP, "I" => DL::TYPE_LONG}
10  POINTER_TYPE = DL::SIZEOF_VOIDP == DL::SIZEOF_LONG_LONG ? 'q*' : 'l!*'
11
12  def initialize(dllname, func, import, export = "0", calltype = :stdcall)
13    @proto = [import].join.tr("VPpNnLlIi", "0SSI").sub(/^(.)0*$/, '\1')
14    handle = DLL[dllname] ||= DL.dlopen(dllname)
15    @func = DL::CFunc.new(handle[func], TYPEMAP[export.tr("VPpNnLlIi", "0SSI")], func, calltype)
16  rescue DL::DLError => e
17    raise LoadError, e.message, e.backtrace
18  end
19
20  def call(*args)
21    import = @proto.split("")
22    args.each_with_index do |x, i|
23      args[i], = [x == 0 ? nil : x].pack("p").unpack(POINTER_TYPE) if import[i] == "S"
24      args[i], = [x].pack("I").unpack("i") if import[i] == "I"
25    end
26    ret, = @func.call(args)
27    return ret || 0
28  end
29
30  alias Call call
31end
32