wasi-module-sdk-go/mem/unmanaged.go

36 lines
915 B
Go
Raw Normal View History

2023-05-08 13:21:31 +00:00
package mem
2023-05-13 15:46:09 +00:00
// #include <stdlib.h>
import "C"
2023-05-08 13:21:31 +00:00
import "unsafe"
2023-05-13 15:46:09 +00:00
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) {
size := C.ulong(len(data))
ptr := unsafe.Pointer(C.malloc(size))
copy(unsafe.Slice((*byte)(ptr), len(data)), data)
return uint32(uintptr(ptr)), uint32(size)
2023-05-08 13:21:31 +00:00
}
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)
}
2023-05-13 15:46:09 +00:00
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)
}