dongtun4268
2017-05-03 17:25
浏览 220
已采纳

从Go中的字符串访问内存地址?

In golang, can I print the value of a memory address from a given string?

For example, if run the following code:

a := "A String"
fmt.Println(&a)

It prints 0x1040c108.

How could I take a string such as 0x1040c108 and print the value of that string stored in the memory? Something like fmt.Println(*0x1040c108)

Is this possible?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • duanping3587 2017-05-03 18:29
    已采纳

    This can be done, but it is a really really REALLY bad idea. Anytime you are importing the unsafe package, you are either doing something wrong, or something really hardcore. I'm hesitant to even answer this, but here goes.

    https://play.golang.org/p/kGWpAiHxzD

    package main
    
    import (
        "fmt"
        "unsafe"
    )
    
    func main() {
        hi := "HI"
        fmt.Println(&hi)
        //address is "0x1040c128"
        var ptr uintptr = 0x1040c128
    
        printPtrString(ptr)
    }
    
    func printPtrString(ptr uintptr) {
        p := unsafe.Pointer(ptr)
        fmt.Println(*(*string)(p))
    }
    

    And yes, this was pretty much taken almost line for line from the unsafe godoc. https://godoc.org/unsafe

    Also note that if/when your memory reference is NOT a go string, everything will come crashing down catastrophically.

    点赞 打赏 评论
  • dongliaoqiang8524 2017-05-03 17:30

    Yes!! you can store the address in a pointer variable and print its value by derefrencing it

    i := "something"
    ptr := &i
    fmt.Println(*ptr)
    

    For accessing the memory using a hard coded address such as 0x1040c108, it is necessary for your program to have access to that memory address otherwise, you will get an error saying invalid indirection of a pointer or segmentation fault.

    点赞 打赏 评论
  • dongmi3203 2017-05-03 18:28
    package main
    
    import "C"
    
    import (
        "log"
        "strconv"
        "unsafe"
    )
    
    func main() {
    
        // parse the string into an integer value
        addr, _ := strconv.ParseInt("0x1040c108", 0, 64)
    
        // cast the integer to a c string pointer
        ptr := (*C.char)(unsafe.Pointer(uintptr(addr)))
    
        // convert to a go string (this will segfault)
        str := C.GoString(ptr)
    
        // print it
        log.Println(str)
    }
    
    点赞 打赏 评论