欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

unsafe.Pointer 和 uintptr

程序员文章站 2022-03-04 18:51:16
...

前言

unsafe.Pointer 是一个万能指针类型,对应c语言中的 void *

unitptr 是一个整数类型,可以进行算术运算

若想要对指针指向的值进行修改,必须转换为uintptr类型,再强转为 (指针)(unsafe.Pointer())

例子

func main() {
	a:=[4]int{0,1,2,3}
	p1:=unsafe.Pointer(&a[1])
	p3:=uintptr(p1)+2*unsafe.Sizeof(a[0])
	*(*int)(unsafe.Pointer(p3))=6
	fmt.Println(a)

//------
    type Person struct {
	name   string
	age    int
	gender bool
    }

    who := Person{"John", 30, true}
    pp := unsafe.Pointer(&who)
    pname := (*string)(unsafe.Pointer(uintptr(pp) + unsafe.Offsetof(who.name)))
    page := (*int)(unsafe.Pointer(uintptr(pp) + unsafe.Offsetof(who.age)))
    pgender := (*bool)(unsafe.Pointer(uintptr(pp) + unsafe.Offsetof(who.gender)))
    *pname = "Alice"
    *page = 28
    *pgender = false
    fmt.Println(who) // {Alice 28 false}
}