我想使用Ruby访问DLL中的函数。我希望使用C的低级访问,同时仍然保留编写Ruby代码的简单性。我该如何做到这一点?
发布于 2009-06-22 00:09:31
看看Win32API
stdlib。它是Windows32API或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
发布于 2015-11-19 06:23:55
你可以使用Fiddle:http://ruby-doc.org/stdlib-2.0.0/libdoc/fiddle/rdoc/Fiddle.html
Fiddle是一个鲜为人知的模块,它是在1.9.x中添加到Ruby的标准库中的。它允许您从Ruby中直接与C库交互。
它通过包装libffi来工作,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
或
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
发布于 2009-06-22 17:35:02
我认为您也可以使用ruby/dl http://groups.google.com/group/comp.lang.ruby/browse_thread/thread/95a483230caf3d39。
或者ffi让它变得更容易,对跨虚拟机更友好:
https://stackoverflow.com/questions/1025086
复制相似问题