Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@tenderlove
Created July 2, 2010 18:17
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tenderlove/461700 to your computer and use it in GitHub Desktop.
Save tenderlove/461700 to your computer and use it in GitHub Desktop.
require 'fiddle'
module FFI
module Library
def ffi_lib *libs
libs.each { |lib| Fiddle.dlopen lib }
end
def attach_function name, arg_types, return_type
f = Fiddle::Function.new(
Fiddle::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)
@flavorjones
Copy link

In Soviet Russia, elegant code writes YOU!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment