Skip to content

Instantly share code, notes, and snippets.

@nanki
Created November 3, 2011 13:59
Show Gist options
  • Save nanki/1336545 to your computer and use it in GitHub Desktop.
Save nanki/1336545 to your computer and use it in GitHub Desktop.
FFI bridge to libruby.
require 'ffi'
module FFI::Ruby
class Value
class << self
extend ::FFI::Library
ffi_lib 'ruby'
attach_function :rb_obj_id, [:pointer], :pointer
attach_function :rb_num2long, [:pointer], :long
def native_type
FFI::Type::POINTER
end
def from_native(value, ctx=nil)
id =
if value.address & 0x0f == 0xe
value.address >> 8
else
rb_num2long rb_obj_id value
end
ObjectSpace._id2ref id
end
def to_native(obj, ctx=nil)
id = obj.__id__
case obj
when Symbol
FFI::Pointer.new id << 8 | 0xe
when Fixnum, FalseClass, TrueClass, NilClass
FFI::Pointer.new id
else
FFI::Pointer.new id << 1
end
end
end
end
extend ::FFI::Library
ffi_lib 'ruby'
typedef FFI::Type::Mapped.new(Value), :value
attach_function :rb_ary_new, [], :value
attach_function :rb_ary_to_s, [:value], :value
attach_function :rb_ary_includes, [:value, :value], :value
attach_function :rb_io_puts, [:int, :pointer, :value], :value
attach_variable :rb_cArray, :value
attach_variable :rb_stdout, :value
attach_function :ruby_show_version, [], :void
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment