因此,假设我绝对需要在go中存储0xc0000140f0
的特定内存地址的值。我该怎么做。例如:
package main
import (
"fmt"
"unsafe"
)
func main() {
targetAddress := 0xc0000140f0
loc := (uintptr)(unsafe.Pointer(targetAddress))
p := unsafe.Pointer(loc)
var val int = *((*int)(p))
fmt.Println("Location : ", loc, " Val :", val)
}
这将导致以下错误:
./memory.go:10:33: cannot convert targetAddress (type int) to type unsafe.Pointer
发布于 2021-07-09 18:41:32
正如错误所述,类型转换无效。来自unsafe.Pointer
文档
请注意,“指针”(大写)指的是unsafe.Pointer
,而“指针值”是指常规的Go指针,如*int
。
Go有一个严格的类型系统,因此您需要检查所使用的类型,并注意类型错误。
试图从给定内存地址加载值的代码的正确版本如下:
package main
import (
"fmt"
"unsafe"
)
func main() {
loc := uintptr(0xc0000140f0)
p := unsafe.Pointer(loc)
var val int = *((*int)(p))
fmt.Println("Location : ", loc, " Val :", val)
}
正如标题所示,您还希望存储值,该值如下所示:
*((*int)(p)) = 1234
现在,如果您想要维护该指针以继续使用它,则可以将其存储为常规的Go指针:
var pointer *int = (*int)(p)
val := *pointer // load something
*pointer = 456 // store something
当然,在这里使用int
完全是任意的。您可以使用任何类型,这将确定“值”在此上下文中的含义。
https://stackoverflow.com/questions/68321230
复制相似问题