亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

runtime.Callers 根據運行的位置打印不同的程序計數器

runtime.Callers 根據運行的位置打印不同的程序計數器

Go
汪汪一只貓 2022-07-04 16:51:47
我有下面的代碼,它根據運行的位置打印不同的程序計數器值。代碼:package mainimport (    "fmt"    "runtime")func foo() {    bar()}func bar() {    pcs := make([]uintptr, 10)    _ = runtime.Callers(0, pcs)    for _, pc := range pcs {        fmt.Printf("Value of pc %+v\n", runtime.FuncForPC(pc).Name())    }}func main() {    foo()}運行 usinggo run或編譯的二進制文件時,它會打印 ( main.baris missing)Value of pc runtime.CallersValue of pc runtime.CallersValue of pc main.mainValue of pc main.fooValue of pc runtime.mainValue of pc runtime.goexit從 Visual Studio Code 運行代碼時(僅在調試模式下,它工作正常)Value of pc runtime.CallersValue of pc main.barValue of pc main.fooValue of pc main.mainValue of pc runtime.mainValue of pc runtime.goexit在Playground中運行時,( foo, bar, 兩者都缺失)Value of pc runtime.CallersValue of pc runtime.CallersValue of pc main.mainValue of pc main.mainValue of pc runtime.mainValue of pc runtime.goexit我正在使用一個框架(logrus),它依賴于 PC 的順序來執行一些操作(記錄文件名)。由于 PC 值會根據其運行位置不斷變化,因此它在調試模式下工作,但在使用go run或編譯的二進制文件運行時會失敗。知道是什么導致 PC 加載不同嗎?任何正在啟動的配置或優化?
查看完整描述

1 回答

?
哆啦的時光機

TA貢獻1779條經驗 獲得超6個贊

狀態文件runtime.Callers():


要將這些 PC 轉換為符號信息,例如函數名稱和行號,請使用 CallersFrames。CallersFrames 考慮內聯函數并將返回程序計數器調整為調用程序計數器。不鼓勵直接迭代返回的 PC 切片,就像在任何返回的 PC 上使用 FuncForPC 一樣,因為這些不能考慮內聯或返回程序計數器調整。


Doc建議使用runtime.CallersFrames()從知道并解釋函數內聯的原始計數器獲取函數信息,例如:


pcs := make([]uintptr, 10)

n := runtime.Callers(0, pcs)

pcs = pcs[:n]


frames := runtime.CallersFrames(pcs)

for {

    frame, more := frames.Next()

    if !more {

        break

    }

    fmt.Println("Function:", frame.Function)

}

無論您如何調用/運行它,這都應該輸出(在Go Playground上嘗試):


Function: runtime.Callers

Function: main.bar

Function: main.foo

Function: main.main

Function: runtime.main


查看完整回答
反對 回復 2022-07-04
  • 1 回答
  • 0 關注
  • 279 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號