Skip to content

Instantly share code, notes, and snippets.

@zliang-min
Forked from tenderlove/fiddle_ffi.rb
Created August 21, 2011 06:18
Show Gist options
  • Save zliang-min/1160240 to your computer and use it in GitHub Desktop.
Save zliang-min/1160240 to your computer and use it in GitHub Desktop.
require 'dl'
require 'fiddle'
module FFI
module Library
def ffi_lib *libs
libs.each { |lib| DL.dlopen lib }
end
def attach_function name, arg_types, return_type
f = Fiddle::Function.new(
DL::Handle[name.to_s],
arg_types.map { |x| Fiddle.const_get(:"TYPE_#{x}".upcase) },
Fiddle.const_get(:"TYPE_#{return_type}".upcase)
)
define_singleton_method(name) do |*args|
f.call(*args)
end
end
end
end
class MyLibrary
extend FFI::Library
ffi_lib '/usr/lib/libm.dylib'
attach_function :sin, [:double], :double
end
p MyLibrary.sin(90 * Math::PI / 180)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment