英文:
Assigning a type uintptr to uint64 in Golang
问题
我正在尝试将类型为 uintptr
的变量中的值赋给 Go 中的 uint64
变量。使用以下代码:
myVar = valFromSystem
会出现以下错误:
> 无法将类型为 uintptr
的 valFromSystem
分配给类型为 uint64
的 myVar
而尝试使用以下代码:
myVar = *valFromSystem
会出现以下错误:
> 无效的 valFromSystem
间接引用(类型为 uintptr
)
有没有办法获取 valFromSystem
指向的值并赋给 myVar
?
英文:
I'm trying to assign the value found in a variable of type uintptr
to a uint64
variable in Go. Using
myVar = valFromSystem
gives me
> cannot use valFromSystem
(type uintptr
) as type uint64
in assignment
And trying
myVar = *valFromSystem
gives me
> invalid indirect of valFromSystem (type uintptr)
Is there a way to pull the value pointed to by valFromSystem to assign to myVar
?
答案1
得分: 22
首先,将valFromSystem
转换为unsafe.Pointer
。unsafe.Pointer
可以转换为任何指针类型。接下来,将unsafe.Pointer
转换为指向valFromSystem
指向的数据类型的指针,例如uint64
。
ptrFromSystem = (*uint64)(unsafe.Pointer(valFromSystem))
如果你只想获取指针的值(而不是解引用它),你可以直接进行转换:
uint64FromSystem = uint64(valFromSystem)
不过请记住,在将指针用作整数时,应使用类型uintptr
。
英文:
First, cast valFromSystem
into an unsafe.Pointer
. An unsafe.Pointer
can be casted into any pointer type. Next, cast the unsafe.Pointer
into a pointer to whatever type of data valFromSystem
points to, e.g. an 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论