Created
February 3, 2009 14:26
-
-
Save BanzaiMan/57537 to your computer and use it in GitHub Desktop.
Trying to get FFI to work
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
$ gcc -dynamiclib -o libsimplemath.dylib simple_math.c | |
$ ruby ruby_ffi.rb | |
243.0 | |
9.0 | |
3628800 | |
$ cc -m64 -dynamiclib -install_name libsimplemath.dylib -o libsimplemath.dylib simple_math.c | |
$ jruby -v ruby_ffi.rb jruby 1.2.0 (ruby 1.8.6 patchlevel 287) (2009-02-03 rev 8978) [x86_64-java] | |
243.0 | |
9.0 | |
3628800 | |
$ cc -dynamiclib -install_name libsimplemath.dylib -o libsimplemath.dylib simple_math.c | |
$ jruby -v ruby_ffi.rb jruby 1.2.0 (ruby 1.8.6 patchlevel 287) (2009-02-03 rev 8978) [i386-java] | |
243.0 | |
9.0 | |
3628800 |
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
# from http://www.igvita.com/2009/01/15/bridging-mri-jruby-rubinius-with-ffi/ | |
require 'ffi' | |
class FFIMath | |
extend FFI::Library | |
# load our custom C library and attach | |
# FFI functions to our Ruby runtime | |
ffi_lib "simplemath" | |
functions = [ | |
# method # parameters # return | |
[:power, [:double, :double], :double], | |
[:square_root, [:double], :double], | |
[:ffi_factorial, [:int], :long] | |
] | |
functions.each do |func| | |
begin | |
attach_function(*func) | |
rescue Object => e | |
puts "Could not attach #{func.inspect}, #{e.message}" | |
end | |
end | |
# attach_function :power, [:double, :double], :double | |
end | |
puts FFIMath.power(3,5) # => 243.0 | |
puts FFIMath.square_root(81) # => 9.0 | |
puts FFIMath.ffi_factorial(10) # => 3628800 |
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
/* from http://www.igvita.com/2009/01/15/bridging-mri-jruby-rubinius-with-ffi/ */ | |
// Simple FFI example between C & Ruby | |
#include <math.h> | |
double power(double base, double power) { | |
return pow(base, power); | |
} | |
double square_root(double x) { | |
return sqrt(x); | |
} | |
// custom factorial function which we'll call from Ruby | |
long ffi_factorial(int max) { | |
int i = max, result = 1; | |
while (i >= 2) { | |
result *= i--; | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment