ChrisMan
ChrisMan

Reputation: 91

How do I declare a pointer at a specific memory address in go golang and store a value there

So let's say that I absolutely NEED to store a value at a specific memory address of 0xc0000140f0 in go. How would I do this. For example:

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)
}

This results in the following errors:

./memory.go:10:33: cannot convert targetAddress (type int) to type unsafe.Pointer

Upvotes: 0

Views: 1478

Answers (1)

Hymns For Disco
Hymns For Disco

Reputation: 8395

As the error says, your type conversion is invalid. From the unsafe.Pointer documentation:

  • A pointer value of any type can be converted to a Pointer.
  • A Pointer can be converted to a pointer value of any type.
  • A uintptr can be converted to a Pointer.
  • A Pointer can be converted to a uintptr.

Note that "Pointer" (caps) refers to unsafe.Pointer, while "pointer value" refers to regular Go pointers like *int

Go has a strict type system, so you need to check the appropriate types for what you're using, and pay attention to type errors.

The correct version of your code, which tries to load the value from the given memory address, is this:

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)
}

As the title suggests, you also want to store a value, which would look like this:

*((*int)(p)) = 1234

Now if you want to maintain that pointer to keep using it, you can store it as a regular Go pointer:

var pointer *int = (*int)(p)
val := *pointer // load something
*pointer = 456 // store something

Of course, the use of int here is completely arbitrary. You could use any type, which will determine the meaning of "a value" in this context.

Upvotes: 6

Related Questions