
Untitled
By: a guest on Jan 28th, 2012 | syntax:
None | size: 0.97 KB | hits: 9 | expires: Never
require 'wilson'
require 'inline'
require 'test/unit'
class Object
@@asm = {}
def asm(name, *args, &block)
code = @@asm[name] ||= assemble(&block).to_ptr
return execute(code) # TODO: args
end
inline(:C) do |b|
b.prefix "typedef long (*fn_ptr)();"
b.include '"dl.h"'
b.c "
VALUE execute(VALUE code) {
return ((fn_ptr)(RDLPTR(code)->ptr))();
}
"
end
end
class Mockup
def example
n = 1000
# the following asm block becomes the machine code:
# 5589E5B800000000403DE803000075F801C040C9C3
asm :count_to_1000 do # TODO: need a better way to cache machine code
eax.mov 0
count = self.label
eax.inc
eax.cmp n
jne count
to_ruby eax
end
end
end
class TestMockup < Test::Unit::TestCase
def test_example
assert_equal 1000, Mockup.new.example
end
def test_example_twice
assert_equal 1000, Mockup.new.example
end
end