我有下面的代碼,它根據運行的位置打印不同的程序計數器值。代碼: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
- 1 回答
- 0 關注
- 279 瀏覽
添加回答
舉報
0/150
提交
取消