有没有一种方法可以将RubyVM::InstructionSequence存储到文件中并在以后读取?
我尝试Marshal.dump
失败。我收到以下错误:
`dump': no _dump_data is defined for class RubyVM::InstructionSequence (TypeError)
最佳答案
是的,有办法。
首先,您需要使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
因为
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 !"
那就是所有的人;)
关于ruby - 如何存储和读取RubyVM::InstructionSequence?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30562292/