Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

unsafe.Pointer的使用 #12

Open
xpzouying opened this issue Sep 2, 2020 · 1 comment
Open

unsafe.Pointer的使用 #12

xpzouying opened this issue Sep 2, 2020 · 1 comment

Comments

@xpzouying
Copy link
Owner

unsafe.Pointer访问数组

当前有个[]int数组对象,如何通过unsafe.Pointer直接访问对象中的元素。

func accessSlice() {
	// init slice
	a1 := make([]int, 10, 10)
	for i := 0; i < 10; i++ {
		a1[i] = 100 + i
	}

	// access
	for i := 0; i < 10; i++ {
		v := *(*int)(unsafe.Pointer(&a1[i]))

		println(v)
	}
}
@xpzouying
Copy link
Owner Author

unsafe.Pointer访问结构体

func accessStruct() {
	type Friends struct {
		Name string
		Age  int
	}

	name := "zy"
	age := 18
	f1 := Friends{Name: name, Age: age}

	log.Printf("sizeof(Friends): %d, sizeof(string)=%d, sizeof(int)=%d", unsafe.Sizeof(f1), unsafe.Sizeof(name), unsafe.Sizeof(age))

	log.Printf("before update f1: %+v", f1)

	// 指针指向f1对象
	f1Ptr := unsafe.Pointer(&f1)

	// 方法1: f1对象的首地址 + name的大小,等于Age元素
	agePtr := unsafe.Pointer((uintptr(f1Ptr) + unsafe.Sizeof(name)))
	*(*int)(agePtr) = 20
	log.Printf("after update f1: %+v", f1)

	// 方法2:使用unsafe.Offsetof 访问Age元素
	agePtr = unsafe.Pointer((uintptr(f1Ptr) + unsafe.Offsetof(f1.Age)))
	*(*int)(agePtr) = 30
	log.Printf("after update f1: %+v", f1)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant