使用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)
}





免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM