简体   繁体   English

在 Golang 中将类型 uintptr 分配给 uint64

[英]Assigning a type uintptr to uint64 in Golang

I'm trying to assign the value found in a variable of type uintptr to a uint64 variable in Go.我试图将在uintptr类型的变量中找到的值分配给 Go 中的uint64变量。 Using使用

myVar = valFromSystem

gives me给我

cannot use valFromSystem (type uintptr ) as type uint64 in assignment不能在赋值中使用valFromSystem (类型uintptr )作为类型uint64

And trying并尝试

myVar = *valFromSystem

gives me给我

invalid indirect of valFromSystem (type uintptr) valFromSystem 的无效间接(类型 uintptr)

Is there a way to pull the value pointed to by valFromSystem to assign to myVar ?有没有办法拉取 valFromSystem 指向的值以分配给myVar

First, cast valFromSystem into an unsafe.Pointer .首先,将valFromSystem转换为unsafe.Pointer An unsafe.Pointer can be casted into any pointer type. unsafe.Pointer可以转换为任何指针类型。 Next, cast the unsafe.Pointer into a pointer to whatever type of data valFromSystem points to, eg an uint64 .接着,施放unsafe.Pointer成指针到任何类型的数据valFromSystem来分,例如一个uint64

ptrFromSystem = (*uint64)(unsafe.Pointer(valFromSystem))

If you just want to get the value of the pointer (without dereferencing it), you can use a direct cast:如果只想获取指针的值(不取消引用),可以使用直接转换:

uint64FromSystem = uint64(valFromSystem)

Though remember that you should use the type uintptr when using pointers as integers.但请记住,当将指针用作整数时,您应该使用uintptr类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM