2009-06-22 183 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以上的答案。