13

Assume there is a string holding the address of an uint64 type variable, can we parse this address back to an *uint64?

For example:

i := uint64(23473824)
ip := &i
str := fmt.Sprintf("%v", ip)

u, _ := strconv.ParseUint(str, 0, 64)

u is uint64. How to get pointer out of this value?

Playground link: https://play.golang.org/p/1KXFQcozRk

NatNgs
  • 874
  • 14
  • 25
ecem
  • 3,574
  • 3
  • 27
  • 40
  • I don't understand golang, but is this page helpful (http://stackoverflow.com/questions/5367961/casting-from-one-pointer-to-pointer-type-to-another-in-golang-error)? It deals with casting pointers. – Jonny Mar 10 '15 at 15:26
  • Thank you, but unfortunately they are not related. – ecem Mar 10 '15 at 15:30
  • _but why would you need to do this?_ – Rambatino Apr 21 '18 at 16:38
  • @Rambatino that's a great question, but let's just say I was on the dark side once. – ecem Apr 16 '19 at 16:32

3 Answers3

17

It is as simple as:

number, err := strconv.ParseUint(string("90"), 10, 64)

then do some error checking, hope it helps.

4

You can do it with

 ip = (*uint64)(unsafe.Pointer(uintptr(u)))

playground link

Albeit I don't know what guarantees Go gives you about the validity of such a pointer, nor can I think of any use case where this code should be used..

nos
  • 223,662
  • 58
  • 417
  • 506
4

Based on nos answer.

Although it is technically possible there are reasons not to trust the code you wrote. Garbage collection will use the memory you point to (with string).

Take a look at result of the following code.

package main

import(
    "fmt"
    "strconv"
    "reflect"
    "unsafe"
)

func produce() string {
    i := uint64(23473824)
    ip := &i
    str := fmt.Sprintf("%v", ip)
    fmt.Println(i, ip, str)
    return str
}

func main() {
    str := produce()

    for i := 0; i < 10; i++ {
         x := make([]int, 1024*1024)
         x[0] = i
    }        

    u, _ := strconv.ParseUint(str, 0, 64) 

    ip := (*uint64)(unsafe.Pointer(uintptr(u)))
    fmt.Println(ip,*ip, reflect.TypeOf(u)) // u is uint64, how to get pointer out of this value?
}

https://play.golang.org/p/85XOhsMTf3

Community
  • 1
  • 1
Grzegorz Żur
  • 47,257
  • 14
  • 109
  • 105