1 struct <-> bytes

  1. type MyStruct struct {
  2. a int
  3. b int
  4. }
  5. func main() {
  6. var ms = &MyStruct{a: 1, b: 2}
  7. // struct 转 byte[]
  8. bytes := StructToBytes(ms)
  9. fmt.Printf("%#v\n", bytes)
  10. // byte[] 转 struct
  11. ms2 := (*MyStruct)(BytesToStruct(bytes))
  12. fmt.Printf("%#v", ms2)
  13. }
  14. func StructToBytes(obj interface{}) []byte {
  15. var x reflect.SliceHeader
  16. length := binary.Size(obj)
  17. x.Len = length
  18. x.Cap = length
  19. x.Data = reflect.ValueOf(obj).Pointer()
  20. return *(*[]byte)(unsafe.Pointer(&x))
  21. }
  22. func BytesToStruct(buf []byte) unsafe.Pointer {
  23. return unsafe.Pointer(
  24. (*reflect.SliceHeader)(unsafe.Pointer(&buf)).Data,
  25. )
  26. }
  1. // a_test.go
  2. package haha
  3. import (
  4. "fmt"
  5. "reflect"
  6. "sync"
  7. "sync/atomic"
  8. "testing"
  9. "time"
  10. "unsafe"
  11. )
  12. func TestFloat(t *testing.T) {
  13. i := 10
  14. f := *(*float64)(unsafe.Pointer(&i))
  15. fmt.Println(f, reflect.TypeOf(f))
  16. }
  17. type MyInt int
  18. func TestConvert(t *testing.T) {
  19. a := []int{1, 2, 3, 4}
  20. b := *(*[]MyInt)(unsafe.Pointer(&a))
  21. fmt.Println(b) // [1 2 3 4]
  22. }
  23. func TestAtomic(t *testing.T) {
  24. var shareBufPtr unsafe.Pointer
  25. writeDataFn := func() {
  26. data := []int{}
  27. for i := 0; i < 100; i++ {
  28. data = append(data, i)
  29. }
  30. // 使shareBufPtr指向data
  31. atomic.StorePointer(&shareBufPtr, unsafe.Pointer(&data))
  32. }
  33. readDataFn := func() {
  34. data := atomic.LoadPointer(&shareBufPtr)
  35. fmt.Println(data, *(*[]int)(data))
  36. }
  37. var wg sync.WaitGroup
  38. writeDataFn()
  39. for i := 0; i < 10; i++ {
  40. wg.Add(1)
  41. go func() {
  42. for i := 0; i < 10; i++ {
  43. writeDataFn()
  44. time.Sleep(time.Microsecond * 100) // 100us
  45. }
  46. wg.Done()
  47. }()
  48. wg.Add(1)
  49. go func() {
  50. for i := 0; i < 10; i++ {
  51. readDataFn()
  52. time.Sleep(time.Microsecond * 100) // 100us
  53. }
  54. wg.Done()
  55. }()
  56. }
  57. wg.Wait()
  58. }