如何在GDB中将地址转换为类型并打印(针对Golang)

6
这是段代码:
package main

import (
    "fmt"
)

type TestType struct {
    a int
    b int
}

func main() {
    var testType TestType = TestType{1, 2}
    fmt.Println(testType)
}

以下是 gdb 调试输出:

(gdb) r
Starting program: /home/bzhang/common/src/go/src/test/testBinary 

Breakpoint 1, main.main () at /home/bzhang/common/src/go/src/test/main.go:14
14              fmt.Println(testType)
(gdb) p testType
$1 = {a = 1, b = 2}
(gdb) p &testType
$2 = (main.TestType *) 0xc820059ee8
(gdb) p ('main.TestType'*) 0xc820059ee8
A syntax error in expression, near `) 0xc820059ee8'.
(gdb) p ('TestType'*) 0xc820059ee8     
A syntax error in expression, near `) 0xc820059ee8'.
(gdb) whatis testType
type = main.TestType
(gdb) 

当然,我知道可以直接打印testType。但是如果它是一个局部变量,有时候它的值不能直接被打印出来,只有它的地址是可用的。因此,我想在指示其类型的情况下打印它的值。但是似乎这样不起作用。 感谢您的帮助!

gdb在处理go语言时效果不佳,可以尝试使用godebug作为替代方案。或者您也可以尝试cgdb - Mark
1个回答

1

Delve工具比gdb更好。https://github.com/go-delve/delve

  1. 安装delve
go get -u github.com/go-delve/delve/cmd/dlv
  1. 在 main.go 中移动路径
cd $GOPATH/src/YOUPROJECT/main.go
  1. 调试深入
$GOPATH/bin/delve debug main.go

断点主函数
Type 'help' for list of commands.
(dlv) b main.main
Breakpoint 1 set at 0x4a7bbf for main.main() main.go:12
  1. 运行
(dlv) c
> main.main() main.go:12 (hits goroutine(1):1 total:1) (PC: 0x4a7bbf)
     7: type TestType struct {
     8:         a int
     9:         b int
    10: }
    11:
=>  12: func main() {
    13:         var testType TestType = TestType{1, 2}
    14:         fmt.Println(testType)
    15: }

断点在第14行。
(dlv) b 14
Breakpoint 2 set at 0x4a7bf0 for main.main() main.go:14
  1. 继续执行
(dlv) c
> main.main() main.go:14 (hits goroutine(1):1 total:1) (PC: 0x4a7bf0)
     9:         b int
    10: }
    11:
    12: func main() {
    13:         var testType TestType = TestType{1, 2}
=>  14:         fmt.Println(testType)
    15: }
  1. 显示数值
(dlv) locals
testType = main.TestType {a: 1, b: 2}

最后,使用goland,vscode进行调试更加方便。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接