如何存储指针指向的地址?
我正在尝试创建我创建的对象的地址映射及其分配时间。键是调用new()
返回的地址。如何获取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
}
请告诉我映射中关键字段的类型应该是什么,以便我可以存储 new()
返回的地址?我计划将 new()
与不同类型一起使用,获取分配的地址并将其与创建时间进行映射。
I am trying to create a map of addresses of objects that I create with the time at which it is allocated. The key is the address returned by the call to new()
. How do I get the address returned by 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 the key field in the map so that I can store the address returned by new()
? I plan to use new()
with different types, get the allocated address and map it with the creation time.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
unsafe
包中的Pointer
类型,但包名称暗示了它是不安全的。地址本身是一个不透明的东西,实际上单独使用地址值来进行映射几乎没有什么用处,最好使用类型和地址的元组。这就是unsafe.Reflect
为您提供的。reflect
包为您提供了UnsafeAddr
函数以及更多功能。我建议您阅读
reflect
和unsafe
包的包文档。You can use the type
Pointer
from theunsafe
package, but that is, the package name implies it, unsafe. The address itself is a opaque thing and there's only little use in actually using a address value alone for a map, better use a tuple of type and address. That's whatunsafe.Reflect
does provide you. The packagereflect
offers you the functionUnsafeAddr
and a lot more.I suggest you read the package documentation for
reflect
andunsafe
packages.使用 uintptr,一个足够大的无符号整数来存储指针值的未解释位,如下所示内存映射键类型。
例如,
输出:
Use uintptr, an unsigned integer large enough to store the uninterpreted bits of a pointer value, as the memory map key type.
For example,
Output: