当前位置: 代码迷 >> 综合 >> Golang 指针(unsafe.Pointer、uintptr)
  详细解决方案

Golang 指针(unsafe.Pointer、uintptr)

热度:22   发布时间:2023-11-26 22:24:20.0
package mainimport ("fmt""unsafe"
)func main() {
    //指针//符号: 取址& 取值*//go指针只能读,不能修改指针的值addr := "沙河"addrP := &addrfmt.Printf("类型:%T,变量值:%v,指向的值:%v \n", addrP, addrP, *addrP)//类型:*string,变量值:0xc00004e230,指向的值:沙河fmt.Println("=============")//修改指针的值:var arr = []int32{
    11, 22, 33}fmt.Println("1.获得arr[0]的指针:")var ptr = &arr[0]fmt.Printf("&arr[0]的类型是:%T,值是:%v\n", ptr, ptr) //*int32 0xc0000140d0fmt.Println("2.将*int32指针转换成unsafe.Pointer类型的指针:")ptr_first_unsafe_point := unsafe.Pointer(ptr)fmt.Printf("ptr_first_unsafe_point的类型是:%T,值是:%v\n", ptr_first_unsafe_point, ptr_first_unsafe_point) //unsafe.Pointer 0xc0000140d0fmt.Println("3.将unsafe.Pointer指针转换成uintptr类型的指针:")ptr_uintptr_first_unsafe_point := uintptr(ptr_first_unsafe_point)fmt.Printf("ptr_uintptr_first_unsafe_point的类型是:%T,值是:%v\n", ptr_uintptr_first_unsafe_point, ptr_uintptr_first_unsafe_point) //uintptr 824633802960fmt.Println("4.将uintptr指针修改,值加4:")//int32 一个数的大小对应 4个字节,所以加4获得数组的第二个元素:22;ptr_uintptr_first_unsafe_point += 4fmt.Printf("ptr_uintptr_first_unsafe_point指针值是%v\n", ptr_uintptr_first_unsafe_point) //824633802964fmt.Println("5.将uintptr指针转换成unsafe.Pointer类型的指针:")ptr_uintptr_second_unsafe_point := unsafe.Pointer(ptr_uintptr_first_unsafe_point)fmt.Printf("ptr_uintptr_second_unsafe_point的类型是:%T,值是:%v\n", ptr_uintptr_second_unsafe_point, ptr_uintptr_second_unsafe_point) //unsafe.Pointer 0xc0000140d4fmt.Println("6.将unsafe.Pointer指针转换成*int32类型的指针:")ptr_after_change := (*int32)(ptr_uintptr_second_unsafe_point)fmt.Printf("ptr_after_change指针值是%v\n", ptr_after_change)     //0xc0000140d4fmt.Printf("ptr_after_change指针指向的值是%v\n", *ptr_after_change) //22/* 结果:1.获得arr[0]的指针:&arr[0]的类型是:*int32,值是:0xc0000140d02.将*int32指针转换成unsafe.Pointer类型的指针:ptr_first_unsafe_point的类型是:unsafe.Pointer,值是:0xc0000140d03.将unsafe.Pointer指针转换成uintptr类型的指针:ptr_uintptr_first_unsafe_point的类型是:uintptr,值是:8246338029604.将uintptr指针修改,值加4:ptr_uintptr_first_unsafe_point指针值是8246338029645.将uintptr指针转换成unsafe.Pointer类型的指针:ptr_uintptr_second_unsafe_point的类型是:unsafe.Pointer,值是:0xc0000140d46.将unsafe.Pointer指针转换成*int32类型的指针:ptr_after_change指针值是0xc0000140d4ptr_after_change指针指向的值是22*//*- unsafe.Pointer只是单纯的通用指针类型,用于转换不同类型指针,它不可以参与指针运算;- 而uintptr是用于指针运算的,GC 不把 uintptr 当指针,也就是说 uintptr 无法持有对象, uintptr 类型的目标会被回收;- unsafe.Pointer 可以和 普通指针 进行相互转换;- unsafe.Pointer 可以和 uintptr 进行相互转换。*/
}
  相关解决方案