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
|
}
|