Question:
Given an unsafe pointer to an array, how can we create an array or a slice from it without incurring the cost of memory copy?
Answer:
Creating a Slice Using Reflect:
The recommended approach is to use the reflect package to create a slice header that points to the same underlying data as the unsafe pointer.
// Create a slice header sh := &reflect.SliceHeader{ Data: p, // Unsafe pointer to the array Len: size, Cap: size, } // Use the slice header to create a slice data := *(*[]byte)(unsafe.Pointer(sh))
Creating an Array Using Reflect:
To create an array (pointer to elements in contiguous memory) from an unsafe pointer, we can first create a slice and then take its address:
// Create a slice data := *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{ Data: p, Len: size, Cap: size, })) // Get the address of the slice (pointer to the first element) arr := (*[size]byte)(unsafe.Pointer(&data[0]))
Caveats and Warnings:
The above is the detailed content of How to Safely Create a Go Slice or Array from an `unsafe.Pointer`?. For more information, please follow other related articles on the PHP Chinese website!