github.com/code-reading/golang@v0.0.0-20220303082512-ba5bc0e589a3/coding/unsafe/zerocopy.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"reflect"
     6  	"unsafe"
     7  )
     8  
     9  func main() {
    10  	txt := "reflect"
    11  	txtBytes := string2bytes(txt)
    12  	ctxt := bytes2string(txtBytes)
    13  	fmt.Println("raw:", txt, " txtBytes:", string(txtBytes), " ctxt:", ctxt)
    14  }
    15  
    16  // output raw: reflect  txtBytes: reflect  ctxt: reflect
    17  
    18  func string2bytes(s string) []byte {
    19  	stringHeander := (*reflect.StringHeader)(unsafe.Pointer(&s))
    20  	bh := reflect.SliceHeader{
    21  		Data: stringHeander.Data,
    22  		Len:  stringHeander.Len,
    23  		Cap:  stringHeander.Len,
    24  	}
    25  	// 将 bh地址转换成unsafe.Pointer
    26  	// 再将unsafe.Pointer 转换成*[]byte指针
    27  	// 在取指针下面的内容 *(*[]byte)()
    28  	return *(*[]byte)(unsafe.Pointer(&bh))
    29  }
    30  
    31  func bytes2string(b []byte) string {
    32  	sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b))
    33  	sh := reflect.StringHeader{
    34  		Data: sliceHeader.Data,
    35  		Len:  sliceHeader.Len,
    36  	}
    37  	return *(*string)(unsafe.Pointer(&sh))
    38  }