如何将`uintptr`传递给`unsafe.Pointer()`以满足`govet`的要求?

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

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

问题

我想将一个uintptr传递给unsafe.Pointer,但是govet告诉我可能会误用unsafe.Pointer。我无法弄清楚如何满足govet的要求。

func Example(base uintptr) byte {
    x := *(*byte)(unsafe.Add(base, 4))
    return x
}

如果我传递&base,govet就不会抱怨,但这会破坏功能,因为它传递的是uintptr的地址。

英文:

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

得分: 1

unsafe.Add函数的第一个参数需要一个unsafe.Pointer类型的指针,但你传递给它的是一个uintptr类型的值。这不是go vet报错,而是go编译器报错,错误信息如下:

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

你可以改为以下方式:

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

以下是一个完整的程序(尽管这个程序可能是不安全的,因为在调用Example函数之前,数组a可能会被垃圾回收)。

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]))))
}
英文:

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

huangapple
  • 本文由 发表于 2022年12月17日 19:34:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/74833734.html
匿名

发表评论

匿名网友

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

确定