【问题标题】:Access byte code generated by ruby for sample program访问 ruby​​ 为示例程序生成的字节码
【发布时间】:2015-10-17 15:53:17
【问题描述】:

有没有办法访问 Ruby 程序为以下示例代码创建的字节码?

x=1
x.to_s
puts x

【问题讨论】:

    标签: ruby bytecode


    【解决方案1】:

    这将显示 YARV 指令

    code = <<END
    x=1
    x.to_s
    puts x
    END
    puts RubyVM::InstructionSequence.compile(code).disasm
    

    如果您想了解更多相关信息,可以查找显微镜下的红宝石

    一书

    这将是输出

    1.9.3-p547 :012 > code = <<END
    1.9.3-p547 :013"> x=1
    1.9.3-p547 :014"> x.to_s
    1.9.3-p547 :015"> puts x
    1.9.3-p547 :016"> END
     => "x=1\nx.to_s\nputs x\n" 
    1.9.3-p547 :017 > puts RubyVM::InstructionSequence.compile(code).disasm
    == disasm: <RubyVM::InstructionSequence:<compiled>@<compiled>>==========
    local table (size: 2, argc: 0 [opts: 0, rest: -1, post: 0, block: -1] s1)
    [ 2] x          
    0000 trace            1                                               (   1)
    0002 putobject        1
    0004 setlocal         x
    0006 trace            1                                               (   2)
    0008 getlocal         x
    0010 send             :to_s, 0, nil, 0, <ic:0>
    0016 pop              
    0017 trace            1                                               (   3)
    0019 putself          
    0020 getlocal         x
    0022 send             :puts, 1, nil, 8, <ic:1>
    0028 leave          
    

    【讨论】:

      【解决方案2】:

      如果您使用的是 Rubinius,您可以像这样运行它并获取字节码:

      $ rbx compile simple.rb -o simple.bytecode
      

      你可以看到一个全面的解释here和一个关于Rubinius编译的解释here

      【讨论】:

      • 我正在使用 MRI,我想将 MRI 将我的示例代码转换为字节或直接解释它
      • 我不认为 MRI 正在编译为字节码。看到这个答案:stackoverflow.com/questions/717490/…
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多