我如何从Ruby调用Windows DLL函数?

我想使用Ruby访问DLL中的函数。 我想使用C的低级访问,同时仍然保持编写Ruby代码的简单性。 我如何做到这一点?

看看Win32API stdlib。 这是一个相当简单(但神秘)的Windows 32 API或DLL的接口。

文档在这里 ,一些例子在这里 。 给你一个口味:

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

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

Fiddle是一个鲜为人知的模块,它被添加到1.9.x的Ruby标准库中。 它允许你直接与Ruby的C库进行交互。

它通过封装libffi(一种流行的C库)来工作,该库允许以一种语言编写的代码调用另一种语言编写的方法。 如果您还没有听说过,“ffi”代表“外部功能接口”。 而且你不仅限于C.一旦你学习小提琴,你可以使用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 

Daniel Berger有win32-API “Win32API的替代品”。 然而,看起来它可能不会保持现状,因为他已经把它留给了开源社区。 它自2015年3月18日以来一直没有更新。它支持到这个答案的红宝石2.2。