英文:
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]))))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论