当前位置:网站首页>The use of go unsafe

The use of go unsafe

2022-06-23 21:28:00 It workers

Explain not to arrange pointers for :

  unsafe.Pointer In fact, it's similar C Of void *, stay golang Is used for a variety of pointer conversion bridge .uintptr yes golang Built in type , It's an integer that can store pointers ,uintptr The bottom type of is int, It and unsafe.Pointer Can be converted to each other .

   Under normal circumstances go Structure private variables in a language cannot be accessed or modified directly , But it can go through unsafe To directly access or modify any variable

package main
 
import (
	_ "ORMTest/routers"
	"fmt"
	"unsafe"
)
 
func main() {
	d := struct {
		s string
		i int
	}{"abc", 100}
	p := uintptr(unsafe.Pointer(&d)) // *struct -> Pointer -> uintptr
	p += unsafe.Offsetof(d.s)        // uintptr + offset
 
	p2 := unsafe.Pointer(p) // uintptr -> Pointer
	px := (*int)(p2)        // Pointer -> *int
	*px = 200               // d.s = 200
	fmt.Printf("%#v\n", d)
}

Output :

{s string;x int}{s:"abc",x:200}

原网站

版权声明
本文为[It workers]所创,转载请带上原文链接,感谢
https://yzsam.com/2021/12/202112241122317504.html