package mem import ( "sync" "unsafe" ) var ( alivePointers = map[uintptr][]byte{} pointersLock sync.Mutex ) func DataToManagedPtr(data []byte) (ptr uint32, size uint32) { uptr := unsafe.Pointer(unsafe.SliceData(data)) return uint32(uintptr(uptr)), uint32(len(data)) } func DataToUnmanagedPtr(data []byte) (uint32, uint32) { pointersLock.Lock() defer pointersLock.Unlock() buf := make([]byte, len(data)) copy(buf, data) ptr := &buf[0] unsafePtr := uintptr(unsafe.Pointer(ptr)) alivePointers[unsafePtr] = buf return uint32(unsafePtr), uint32(len(data)) } func DataFromPtr(ptr, size uint32) []byte { p := unsafe.Pointer(uintptr(ptr)) return unsafe.Slice((*byte)(p), int(size)) } func PtrToData(ptr uint32, size uint32) []byte { return unsafe.Slice((*byte)(unsafe.Pointer(uintptr(ptr))), size) } func UnifyPtrSize(ptr, size uint32) uint64 { return (uint64(ptr) << uint64(32)) | uint64(size) } func UnifiedPtrToSizePtr(uint64ptr uint64) (ptr uint32, size uint32) { return uint32(uint64ptr >> 32), uint32(uint64ptr) } //export allocate func Allocate(size uint32) uintptr { pointersLock.Lock() defer pointersLock.Unlock() buf := make([]byte, size) unsafePtr := uintptr(unsafe.Pointer(unsafe.SliceData(buf))) alivePointers[unsafePtr] = buf return unsafePtr } //export deallocate func Deallocate(ptr uintptr) { pointersLock.Lock() defer pointersLock.Unlock() delete(alivePointers, ptr) }