我想使用Ruby访问DLL中的函数。我希望在保留编写Ruby代码简易性的同时,使用C的低级访问。我该如何实现?
require 'fiddle'
libm = Fiddle.dlopen('/lib/libm.so.6')
floor = Fiddle::Function.new(
libm['floor'],
[Fiddle::TYPE_DOUBLE],
Fiddle::TYPE_DOUBLE
)
puts floor.call(3.14159) #=> 3.0
或者
require 'fiddle'
require 'fiddle/import'
module Logs
extend Fiddle::Importer
dlload '/usr/lib/libSystem.dylib'
extern 'double log(double)'
extern 'double log10(double)'
extern 'double log2(double)'
end
# We can call the external functions as if they were ruby methods!
puts Logs.log(10) # 2.302585092994046
puts Logs.log10(10) # 1.0
puts Logs.log2(10) # 3.321928094887362
这里有一个开源的win32-api,由Hiroshi Hatake和Daniel Berger创建,是Win32API的替代品。它适用于Ruby 1.8、1.9和2.X版本。