2007-12-02 21:53:13 -05:00
|
|
|
# -*- ruby -*-
|
2016-06-26 06:35:53 -04:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2007-12-02 21:53:13 -05:00
|
|
|
# for backward compatibility
|
2018-04-02 08:39:01 -04:00
|
|
|
warn "Win32API is deprecated after Ruby 1.9.1; use fiddle directly instead", uplevel: 2
|
2007-12-02 21:53:13 -05:00
|
|
|
|
2014-11-04 07:26:19 -05:00
|
|
|
require 'fiddle/import'
|
2007-12-02 21:53:13 -05:00
|
|
|
|
|
|
|
class Win32API
|
|
|
|
DLL = {}
|
2014-10-31 17:13:09 -04:00
|
|
|
TYPEMAP = {"0" => Fiddle::TYPE_VOID, "S" => Fiddle::TYPE_VOIDP, "I" => Fiddle::TYPE_LONG}
|
|
|
|
POINTER_TYPE = Fiddle::SIZEOF_VOIDP == Fiddle::SIZEOF_LONG_LONG ? 'q*' : 'l!*'
|
2007-12-02 21:53:13 -05:00
|
|
|
|
2016-06-26 06:35:53 -04:00
|
|
|
WIN32_TYPES = "VPpNnLlIi"
|
|
|
|
DL_TYPES = "0SSI"
|
|
|
|
|
2009-03-11 04:27:21 -04:00
|
|
|
def initialize(dllname, func, import, export = "0", calltype = :stdcall)
|
2016-06-26 06:35:53 -04:00
|
|
|
@proto = [import].join.tr(WIN32_TYPES, DL_TYPES).sub(/^(.)0*$/, '\1')
|
|
|
|
import = @proto.chars.map {|win_type| TYPEMAP[win_type.tr(WIN32_TYPES, DL_TYPES)]}
|
|
|
|
export = TYPEMAP[export.tr(WIN32_TYPES, DL_TYPES)]
|
|
|
|
calltype = Fiddle::Importer.const_get(:CALL_TYPE_TO_ABI)[calltype]
|
|
|
|
|
2016-06-25 21:20:27 -04:00
|
|
|
handle = DLL[dllname] ||=
|
|
|
|
begin
|
|
|
|
Fiddle.dlopen(dllname)
|
|
|
|
rescue Fiddle::DLError
|
|
|
|
raise unless File.extname(dllname).empty?
|
|
|
|
Fiddle.dlopen(dllname + ".dll")
|
|
|
|
end
|
2014-10-31 17:13:09 -04:00
|
|
|
|
2016-06-26 06:35:53 -04:00
|
|
|
@func = Fiddle::Function.new(handle[func], import, export, calltype)
|
2014-10-31 17:13:09 -04:00
|
|
|
rescue Fiddle::DLError => e
|
2009-02-13 09:37:11 -05:00
|
|
|
raise LoadError, e.message, e.backtrace
|
2007-12-02 21:53:13 -05:00
|
|
|
end
|
|
|
|
|
|
|
|
def call(*args)
|
|
|
|
import = @proto.split("")
|
|
|
|
args.each_with_index do |x, i|
|
2012-11-05 09:00:41 -05:00
|
|
|
args[i], = [x == 0 ? nil : x].pack("p").unpack(POINTER_TYPE) if import[i] == "S"
|
2007-12-02 21:53:13 -05:00
|
|
|
args[i], = [x].pack("I").unpack("i") if import[i] == "I"
|
|
|
|
end
|
2014-12-16 11:08:16 -05:00
|
|
|
ret, = @func.call(*args)
|
2007-12-02 21:53:13 -05:00
|
|
|
return ret || 0
|
|
|
|
end
|
|
|
|
|
|
|
|
alias Call call
|
|
|
|
end
|