chenshijun
2020-03-31 e917fdc164d5ea164e97ede2d25b621b3b5322ff
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package shmqueue
 
import (
    "reflect"
    "unsafe"
)
 
// []byte struct
type ShmDataInfo struct {
    Capacity uint32
    Cache    []byte
}
 
// shmData2Info convert []byte to *ShmDataInfo
func shmData2Info(b []byte) *ShmDataInfo {
    return (*ShmDataInfo)(unsafe.Pointer(
        (*reflect.SliceHeader)(unsafe.Pointer(&b)).Data,
    ))
}
 
// ConvertToSlice convert to []byte
func ptr2Slice(s unsafe.Pointer, size int) []byte {
    var x reflect.SliceHeader
    x.Len = size
    x.Cap = size
    x.Data = uintptr(s)
    return *(*[]byte)(unsafe.Pointer(&x))
}
 
//WriteShmData   data待写入的数据;   shmId:共享内存id,只attach,不create
func WriteShmData(data []byte, shmId int) error {
    shmData,err := Attach(shmId)
    if err != nil {
        return err
    }
    sdi := shmData2Info(shmData)
    if len(data) <= len(shmData) {
        sdi.Capacity = uint32(len(data))
    } else {
        sdi.Capacity = uint32(len(shmData))
    }
 
    tmpData := ptr2Slice(unsafe.Pointer(&sdi.Cache), int(sdi.Capacity))
    copy(tmpData, data)
 
    return nil
}
 
//ReadShmData attach到shmId对应的共享内存,并读出数据[]byte
func ReadShmData(shmId int) ([]byte,error) {
    shmData,err := Attach(shmId)
    if err != nil {
        return nil,err
    }
 
    sdi := shmData2Info(shmData)
    tmpData := ptr2Slice(unsafe.Pointer(&sdi.Cache), int(sdi.Capacity))
 
    return tmpData, nil
}