-
-
Save zliang-min/1160240 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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