Skip to content

Instantly share code, notes, and snippets.

@thinkerbot
Created November 24, 2009 18:52
Show Gist options
  • Save thinkerbot/242104 to your computer and use it in GitHub Desktop.
Save thinkerbot/242104 to your computer and use it in GitHub Desktop.
A Simple FFI example on OS X
#"" An FFI example on Mac 10.5.8
#
# % gcc --version
# i686-apple-darwin9-gcc-4.0.1 (GCC) 4.0.1 (Apple Inc. build 5465)
#
# Setup a source file
#
require 'fileutils'
Dir.glob("circle.*").each {|file| FileUtils.rm(file)}
File.open("circle.c", "w") do |file|
file << %q{
double circularArea( double r )
{
const double pi = 3.14159;
return pi * r * r;
}}
end
#
# Build the dynamic library
# (on mac -dynamiclib is required instead of -shared)
#
def sh(cmd); puts cmd; system(cmd) end
puts "Building:"
sh "gcc -c circle.c"
sh "gcc -dynamiclib -o circle.dylib circle.c"
#
# Load the library with FFI
#
# using ffi 0.5.0
require 'ffi'
module Circle
extend FFI::Library
ffi_lib "circle.dylib"
attach_function :circularArea, [:double ], :double
end
puts
puts "Test:"
puts "area(3) = #{Circle.circularArea(3)}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment