Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created October 10, 2017 20:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save havenwood/206989c1fac2de95c5ca1d8ed34f82ec to your computer and use it in GitHub Desktop.
Save havenwood/206989c1fac2de95c5ca1d8ed34f82ec to your computer and use it in GitHub Desktop.
require 'fiddle'
class Object
def cast(as)
# Make sure iv table of the new class gets initialized.
as.new.send(:instance_variable_set, :@nil, nil)
rbasic = Fiddle::Pointer.new(__id__ << 1)
as_klass = Fiddle::Pointer.new(as.__id__ << 1)
# Ruby guarantees sizeof(VALUE) == sizeof(void *)
rbasic[Fiddle::SIZEOF_VOIDP, Fiddle::SIZEOF_VOIDP] = as_klass.ref.to_str(Fiddle::SIZEOF_VOIDP)
end
end
class Base
def initialize
@ivar = 42
end
attr_reader :ivar
end
class Derived < Base
def initialize
@ivar = 23
end
def bark
puts @ivar
end
end
obj = Base.new
obj.cast(Derived)
obj.bark
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment