Home > Backend Development > Golang > How to Safely Create a Go Slice or Array from an `unsafe.Pointer`?

How to Safely Create a Go Slice or Array from an `unsafe.Pointer`?

Susan Sarandon
Release: 2024-12-10 12:08:09
Original
981 people have browsed it

How to Safely Create a Go Slice or Array from an `unsafe.Pointer`?

How to create an array or a slice from an array unsafe.Pointer in Go?

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))
Copy after login

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]))
Copy after login

Caveats and Warnings:

  • Ensure that the lifetime of the original array is managed to prevent unexpected memory access.
  • Avoid using uintptr variables as references to objects, as garbage collection may occur unexpectedly.
  • Use runtime.KeepAlive() if necessary to prevent the original array from being garbage collected before it is referenced by the slice or array created from the unsafe pointer.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template