Created
October 10, 2017 20:23
-
-
Save havenwood/206989c1fac2de95c5ca1d8ed34f82ec 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 '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