Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I call Windows DLL functions from Ruby?

Tags:

c

windows

ruby

dll

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?

like image 612
Jeremy Mack Avatar asked Jun 22 '09 00:06

Jeremy Mack


2 Answers

Have a look at Win32API stdlib. It's a fairly easy (but arcane) interface to the Windows 32 API, or DLLs.

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 
like image 179
molf Avatar answered Oct 14 '22 02:10

molf


You can use Fiddle: 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.

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.

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

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
like image 24
marsh Avatar answered Oct 14 '22 02:10

marsh