How do i pass uintptr to unsafe.Pointer() satisfying govet

545 views Asked by At

I want to pass a uintptr to unsafe.Pointer but govet is telling me possible misuse of unsafe.Pointer. I can't figure out how to satisfy govet.


func Example(base uintptr) byte {

    x := *(*byte)(unsafe.Add(base, 4))

    return x

}

If i pass &base govet does to complain but breaks the functionality because it is passing the address of uintptr.

1

There are 1 answers

0
Paul Hankin On

unsafe.Add takes an unsafe.Pointer as its first argument, but you're passing it a uintptr. It's not govet that complains, it's the go compiler, and here is the error:

cannot use base (variable of type uintptr) as type unsafe.Pointer in argument to unsafe.Add

Instead:

x := *(*byte)unsafe.Pointer(base + 4)

As a complete program (although this program is probably unsound because the a array could in principle be garbage collected before Example is called).

package main

import (
    "fmt"
    "unsafe"
)

func Example(base uintptr) byte {
    return *(*byte)(unsafe.Pointer(base + 4))
}

func main() {
    a := [10]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    fmt.Println(Example(uintptr(unsafe.Pointer(&a[0]))))
}