How to save the address pointed to by a pointer?

I am trying to create an address map of the objects that I create, with the time at which it was allocated. The key is the address returned by the call new(). How to get the address returned new()?

type T struct{a, b int }

func main(){

        var t int64 = time.Nanoseconds()
        memmap := make(map[uint8]int64)
        fmt.Printf("%d\n", t)
        var ptr *T = new(T)
        ptr.a = 1
        ptr.b = 2
        fmt.Printf("%d %d %p %T\n", ptr.a, ptr.b, ptr, ptr)
        //memmap[ptr] = t //gives error
        //var temp uint8 = ptr//gives error
}

Please tell me what should be the type of key field on the map so that I can save the address returned new()? I plan to use new()with different types, get a dedicated address and match it with the time of creation.

+3
source share
2 answers

Pointer unsafe, , , . , . , unsafe.Reflect . reflect UnsafeAddr .

reflect unsafe.

+6

uintptr, , , .

,

package main

import (
    "fmt"
    "time"
    "unsafe"
)

type T struct{ a, b int }

func main() {
    memmap := make(map[uintptr]int64)

    pT := new(T)
    memmap[uintptr(unsafe.Pointer(pT))] = time.Nanoseconds()
    pT.a = 1
    pT.b = 2
    fmt.Printf("%d %d %p %T\n", pT.a, pT.b, pT, pT)

    pI := new(int)
    memmap[uintptr(unsafe.Pointer(pI))] = time.Nanoseconds()
    *pI = 42
    fmt.Printf("%d %p %T\n", *pI, pI, pI)

    fmt.Printf("\n%T\n", memmap)
    for k, v := range memmap {
        fmt.Printf("%x: %d\n", k, v)
    }
}

:

1 2 0xf8400001f8 *main.T
42 0xf8400001f0 *int

map[uintptr] int64
f8400001f0: 1306837191421330000
f8400001f8: 1306837191421293000
+3

All Articles