github.com/hedzr/evendeep@v0.4.8/internal/syscalls/uintptr_test.go (about)

     1  package syscalls
     2  
     3  import (
     4  	"fmt"
     5  	"testing"
     6  	"unsafe"
     7  )
     8  
     9  type sample struct {
    10  	a int
    11  	b string
    12  }
    13  
    14  func TestUnsafePointer(t *testing.T) {
    15  	s := &sample{a: 1, b: "test"}
    16  
    17  	// Getting the address of field b in struct s
    18  	p := unsafe.Pointer(uintptr(unsafe.Pointer(s)) + unsafe.Offsetof(s.b))
    19  
    20  	// Typecasting it to a string pointer and printing the value of it
    21  	fmt.Println(*(*string)(p))
    22  
    23  	str := *(*string)(p)
    24  	if str != "test" {
    25  		t.Fail()
    26  	}
    27  
    28  	// Get the address as a uintptr
    29  	startAddress := uintptr(unsafe.Pointer(s))
    30  	fmt.Printf("Start Address of s: %d, %x, %v\n",
    31  		startAddress, startAddress,
    32  		UintptrToString(startAddress),
    33  	)
    34  
    35  	str = UintptrToString(startAddress)
    36  	if u := UintptrFromString(str); u != startAddress {
    37  		t.Fail()
    38  	} else {
    39  
    40  		b := toBytes1(u)
    41  		fmt.Println(b)
    42  		b = toBytes2(&u)
    43  		fmt.Println(b)
    44  
    45  	}
    46  }