2009-06-22 184 views

回答

14

看看Win32API stdlib。這是一個相當簡單(但神祕)的Windows 32 API或DLL接口。

Documentation is here,一些examples here。爲了給你一個味道:

require "Win32API"  
def get_computer_name 
    name = " " * 128 
    size = "128" 
    Win32API.new('kernel32', 'GetComputerName', ['P', 'P'], 'I').call(name, size) 
    name.unpack("A*") 
end 
+3

它工作得很好,除非你的DLL有Win32API無法處理的參數(比如雙打)。然後你會進入Array.unpack噩夢 – SztupY 2009-06-22 00:41:05

+2

Win32API和文檔鏈接已經死了。 – zeboidlund 2014-09-05 09:39:48

8

你可以使用小提琴:http://ruby-doc.org/stdlib-2.0.0/libdoc/fiddle/rdoc/Fiddle.html

小提琴是一個鮮爲人知的模塊,被添加到1.9.x中的Ruby標準庫。它允許您直接與來自Ruby的C庫進行交互。

它通過包裝libffi工作,這是一種流行的C庫,允許用一種語言編寫的代碼調用另一種語言編寫的方法。如果您還沒有聽說過,「ffi」代表「外部功能接口」。而且你不僅限於C.一旦你學習了Fiddle,你可以使用用Rust和其他支持它的語言編寫的庫。

http://blog.honeybadger.io/use-any-c-library-from-ruby-via-fiddle-the-ruby-standard-librarys-best-kept-secret/

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 
2

還有就是win32-api 「落更換爲Win32API的」 由丹尼爾·伯傑。但是,它似乎並未保持最新狀態,因爲他已將它留給了開源社區。它從2015年3月18日起一直沒有更新過。它支持Ruby 2.2以上的答案。