Skip to content

Instantly share code, notes, and snippets.

@nobu
Created March 5, 2017 13:44
Show Gist options
  • Save nobu/afc1fafbf30d0129e8adb3b5630c7f52 to your computer and use it in GitHub Desktop.
Save nobu/afc1fafbf30d0129e8adb3b5630c7f52 to your computer and use it in GitHub Desktop.
#!/usr/local/bin/ruby
require 'open3'
require 'tempfile'
require 'rbconfig'
require 'fiddle/import'
class Sample
def main
func = RbConfig::CONFIG["SYMBOL_PREFIX"]+"sample_add"
src = <<EOS
.text
.globl #{func}
.align 16, 0x90
#{func}:
addl %esi, %edi
movl %edi, %eax
ret
EOS
objfile = Tempfile.new ['rbasm-obj_', '.o'], '/tmp'
objfile.close
IO.popen(%W"clang -x assembler -c -o #{objfile.path} -", "w", umask: 0177) do |stream|
stream.write src
stream.close
end
libfile = Tempfile.new ['rbasm-lib_', '.so'], '/tmp'
libfile.close
system(*%W"clang -shared -o #{libfile.path} #{objfile.path}", umask: 177)
objfile.delete
m = Module.new {
extend Fiddle::Importer
dlload libfile.path
libfile.delete
extern "int sample_add(int, int)"
}
p m.sample_add 1, 2
m.handler.handlers.each {|h|
h.close
}
m = nil
GC.start
end
end
sample = Sample.new
sample.main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment