【问题标题】:how to use RubyVM to compile ruby code to bytecode with require source files?如何使用 RubyVM 将 ruby​​ 代码编译为需要源文件的字节码?
【发布时间】:2020-08-30 17:28:22
【问题描述】:

我有 2 个 ruby​​ 源文件,例如:

A.rb

require "B"

foo

B.rb

 def foo()
  ..
 end

现在我使用代码将 A 编译为字节码(Ruby v2.3.3):

byte_code = RubyVM::InstructionSequence.compile_file "A.rb"
File.binwrite "A.byte", byte_code.to_binary

当我运行字节码时:

byte_code_in_binary = IO.binread "A.byte"
instruction_from_byte_code = RubyVM::InstructionSequence.load_from_binary byte_code_in_binary
instruction_from_byte_code.eval

那么消息是:

   .... in `require': cannot load such file -- B (LoadError)

如果我将 B.rb 编译为字节码,那么 A.byte 如何加载 B.byte ?还是有另一种方法可以将完整的 ruby​​ 项目编译为字节码并运行? Jruby 或一些工具可以实现吗?谢谢。

【问题讨论】:

    标签: ruby bytecode jit


    【解决方案1】:

    问题暂时解决了。答案是:制作一个“code shell”来加载二进制文件,它看起来像:

    文件列表.rb

    $folder="some_folder"
    $main_entry = "main.rb"
    $reqiured_file=
    [
      "file_1.rb",
      "file_2.rb",
      ...
    ]
    

    现在在编译源代码时,它看起来像:

    def write_code(fname, load_filename)
        str = 
    'byte_code_in_binary = IO.binread("'+load_filename+'")
    instruction_from_byte_code = RubyVM::InstructionSequence.load_from_binary byte_code_in_binary
    instruction_from_byte_code.eval'
        f = open(fname, "wb")
        f.write(str)
        f.close()
    end
    
    $LOAD_PATH.unshift(File.dirname(__FILE__))
    require "filelist"
    Dir.mkdir($folder)
    byte_code = RubyVM::InstructionSequence.compile_file $main_entry
    File.binwrite $folder + "/some_binary_file_name", byte_code.to_binary
    
    $required_files.each do |f|
        write_code($folder + "/" + f, some_required_binary_names)
        byte_code = RubyVM::InstructionSequence.compile_file f
        File.binwrite $folder + "/" + some_required_binary_names, byte_code.to_binary
    end
    

    OK 现在需要 ruby​​ 脚本文件看起来像:

    file_1.rb

    byte_code_in_binary = IO.binread("file_1_binary_name") <-- it was real compiled binary file_1.rb
    instruction_from_byte_code = RubyVM::InstructionSequence.load_from_binary byte_code_in_binary
    instruction_from_byte_code.eval
    

    现在我们可以使用“VM 二进制模式”加载所需文件。

    【讨论】:

      猜你喜欢
      • 2014-01-20
      • 2015-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-18
      • 2018-01-31
      • 1970-01-01
      • 2012-08-04
      相关资源
      最近更新 更多