I just run into a problem trying to call a Windows API from Ruby and wanted to document it here so that me and others can benefit from the solution. I was trying to call a Windows API using the excellent dl (I guess it stands for "dynamic load") module (comes with Ruby). Here's the code sample:

require 'dl/import'
module NTKernel
  extend DL::Importable
  dlload "kernel32.dll"
  extern "int GetStdHandle(int)"
end
#get the handle of the standard output
result = NTKernel.GetStdHandle(-11)

Just standard stuff, nothing fancy. MSDN documentation helps with the API declaration and constants. Based on all we know, this should work, no?

Not quite. Ruby has a convention where all methods start with lowercase letters, and dl library silently respects this by renaming GetStdHandle into getStdHandle - ouch!

It took me some time to figure this out - I had to use reflection to see which methods are defined for my module (you can get a list of methods for a class or module by calling methods method).

So the call that works is actually NTKernel.getStdHandle(-11).

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
1 Comments