使用unsafe.Pointer将结构体转为[]byte


package main


import (
    "fmt"
    "unsafe"
)

type TestStructTobytes struct {
    data int64
    s    int8
}
type SliceMock struct {
    addr uintptr
    len  int
    cap  int
}

func main() {
    var testStruct = &TestStructTobytes{100, 'a'}
    Len := unsafe.Sizeof(*testStruct)
    testBytes := &SliceMock{
        addr: uintptr(unsafe.Pointer(testStruct)), //使用unsafe.Pointer作为桥梁使*转为uintptr符合[]byte的底层数据结构
        cap:  int(Len),
        len:  int(Len),
    }
    data := *(*[]byte)(unsafe.Pointer(testBytes)) //想将结构体转为[]byte需要结构体和byte有一样的数据结构SliceMock做到了这点
    fmt.Println("[]byte is : ", data)
}




猜你喜欢

转载自www.cnblogs.com/hualou/p/12069757.html