有没有办法将RubyVM :: InstructionSequence存储到文件中并在以后读取?
我尝试Marshal.dump没有成功.我收到以下错误:
`dump': no _dump_data is defined for class RubyVM::InstructionSequence (TypeError)
Run Code Online (Sandbox Code Playgroud)
Dav*_*ric 12
是的,有一种方法.
首先,您需要make access load方法InstructionSequence,默认情况下禁用:
require 'fiddle'
class RubyVM::InstructionSequence
# Retrieve Ruby Core's C-ext `iseq_load' function address
load_fn_addr = Fiddle::Handle::DEFAULT['rb_iseq_load']
# Retrieve `iseq_load' C function representation
load_fn = Fiddle::Function.new(load_fn_addr,
[Fiddle::TYPE_VOIDP] * 3,
Fiddle::TYPE_VOIDP)
# Make `iseq_load' accessible as `load' class method
define_singleton_method(:load) do |data, parent = nil, opt = nil|
load_fn.call(Fiddle.dlwrap(data), parent, opt).to_value
end
end
Run Code Online (Sandbox Code Playgroud)
因为该RubyVM::InstructionSequence.load方法可以将编译的VM指令作为数组加载,所以您可以自由地将其用于(反)序列化目的:
irb> # compile simple ruby program into its instruction sequence
irb> seq = RubyVM::InstructionSequence.new <<-EOS
irb: p 'Hello, world !'
irb: EOS
=> <RubyVM::InstructionSequence:<compiled>@<compiled>
irb> # serialize sequence as Array instance representation
irb> data = Marshal.dump seq.to_a
=> "\x04\b[\x13\"-YARVInstructionSequence/SimpleDataFormat … ]"
irb> # de-serialize previously serialized sequence
irb> seq_loaded = Marshal.load data
=> ["YARVInstructionSequence/SimpleDataFormat", 2, 2, 1, { … ]
irb> # load deserialized Array back into instruction sequence
irb> new_iseq = RubyVM::InstructionSequence.load seq_loaded
=> <RubyVM::InstructionSequence:<compiled>@<compiled>>
irb> # execute instruction sequence in current context
irb> new_iseq.eval
"Hello, world !"
=> "Hello, world !"
Run Code Online (Sandbox Code Playgroud)
那是所有人;)
鉴于该类的方法有限,您可以尝试的事情也有限。也许你唯一能做的就是将其实例保存为字符串:
puts RubyVM::InstructionSequence.disasm(proc{puts "foo"})
Run Code Online (Sandbox Code Playgroud)
结果:
== disasm: <RubyVM::InstructionSequence:block in irb_binding@(irb)>=====
== catch table
| catch type: redo st: 0002 ed: 0009 sp: 0000 cont: 0002
| catch type: next st: 0002 ed: 0009 sp: 0000 cont: 0009
|------------------------------------------------------------------------
0000 trace 256 ( 1)
0002 trace 1
0004 putself
0005 putstring \"foo\"
0007 opt_send_without_block <callinfo!mid:puts, argc:1, FCALL|ARGS_SIMPLE>
0009 trace 512
0011 leave
Run Code Online (Sandbox Code Playgroud)
当你想反序列化它时,你需要解析这个字符串。
| 归档时间: |
|
| 查看次数: |
860 次 |
| 最近记录: |