如何在 Julia 回溯中显示调用者?

How to show caller in a Julia backtrace?

有没有办法获取 Julia 函数调用者的 file/name/line 信息?

我找到了 this way to get some stacktrace info,如果调用者是另一个函数(但不是主上下文),我会得到 file:line 信息:

module pd

   global g_bTraceOn = true

   export callerOfTraceIt

   function callerOfTraceIt()
     traceit( "hi" ) ;
   end

   function traceit( msg )
      global g_bTraceOn

      if ( g_bTraceOn )
         bt = backtrace() ;
         s = sprint(io->Base.show_backtrace(io, bt))

         println( "debug: $s: $msg" )
      end
   end
end

using pd

callerOfTraceIt( )

这表明:

$ julia bt.jl
debug:
 in traceit at C:\cygwin64\home\Peeter\julia\HarmonicBalance\bt.jl:15
 in callerOfTraceIt at C:\cygwin64\home\Peeter\julia\HarmonicBalance\bt.jl:8
 in include at boot.jl:245
 in include_from_node1 at loading.jl:128
 in process_options at client.jl:285
 in _start at client.jl:354: hi

我真的很喜欢第二个框架(traceit() 的调用者),并且如果它可用的话,我也想要函数名称。

如果您在 traceit 中执行 @show bt,您会发现它只是一个指针列表,每个指针对应一个堆栈帧。那些来自 julia 代码(而不是 C)的堆栈帧由 show_backtrace.

显示

您可以调用 Profile.lookup(uint(bt[1])) 从每个元素中提取 file/function/line 信息:

julia> Profile.lookup(uint(bt[1]))
LineInfo("rec_backtrace","/home/tim/src/julia-old/usr/bin/../lib/libjulia.so",-1,true,140293228378757)

julia> names(Profile.LineInfo)
5-element Array{Symbol,1}:
 :func 
 :file 
 :line 
 :fromC
 :ip   

您可能希望忽略带有 fromC == true 的所有元素。