如何从 Ruby 调用 Windows DLL 函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1025086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I call Windows DLL functions from Ruby?
提问by Jeremy Mack
I want to access functions within a DLL using Ruby. I want to use the low-level access of C while still retaining the simplicity of writing Ruby code. How do I accomplish this?
我想使用 Ruby 访问 DLL 中的函数。我想使用 C 的低级访问,同时仍然保留编写 Ruby 代码的简单性。我该如何实现?
采纳答案by molf
Have a look at Win32API
stdlib. It's a fairly easy (but arcane) interface to the Windows 32 API, or DLLs.
看看标准库Win32API
。它是 Windows 32 API 或 DLL 的一个相当简单(但很神秘)的接口。
Documentation is here, some examples here. To give you a taste:
require "Win32API"
def get_computer_name
name = " " * 128
size = "128"
Win32API.new('kernel32', 'GetComputerName', ['P', 'P'], 'I').call(name, size)
name.unpack("A*")
end
回答by marsh
You can use Fiddle: http://ruby-doc.org/stdlib-2.0.0/libdoc/fiddle/rdoc/Fiddle.html
你可以使用小提琴:http: //ruby-doc.org/stdlib-2.0.0/libdoc/fiddle/rdoc/Fiddle.html
Fiddle is a little-known module that was added to Ruby's standard library in 1.9.x. It allow you to interact directly with C libraries from Ruby.
Fiddle 是一个鲜为人知的模块,它在 1.9.x 中被添加到 Ruby 的标准库中。它允许您直接与来自 Ruby 的 C 库交互。
It works by wrapping libffi, a popular C library that allows code written in one language to call methods written in another. In case you haven't heard of it, "ffi" stands for "foreign function interface." And you're not just limited to C. Once you learn Fiddle, you can use libraries written in Rust and other languages that support it.
它的工作原理是包装 libffi,这是一个流行的 C 库,允许用一种语言编写的代码调用用另一种语言编写的方法。如果您没有听说过,“ffi”代表“外部函数接口”。而且您不仅限于 C。一旦您学习了 Fiddle,您就可以使用用 Rust 和其他支持它的语言编写的库。
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
or
或者
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
回答by rogerdpack
I think you can also use ruby/dl http://groups.google.com/group/comp.lang.ruby/browse_thread/thread/95a483230caf3d39
我想你也可以使用 ruby/dl http://groups.google.com/group/comp.lang.ruby/browse_thread/thread/95a483230caf3d39
or ffi makes it easier and more cross VM friendly:
或 ffi 使它更容易和更跨 VM 友好: