Assigning a type uintptr to uint64 in Golang

huangapple go评论71阅读模式
英文:

Assigning a type uintptr to uint64 in Golang

问题

我正在尝试将类型为 uintptr 的变量中的值赋给 Go 中的 uint64 变量。使用以下代码:

myVar = valFromSystem

会出现以下错误:

> 无法将类型为 uintptrvalFromSystem 分配给类型为 uint64myVar

而尝试使用以下代码:

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.Pointerunsafe.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.

huangapple
  • 本文由 发表于 2014年4月22日 01:56:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/23202864.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定