I'm trying to write a screenshot function for my OpenGL project in Go, I'm using the OpenGL bindings found here:
This is the code I use to make a screenshot, or well, it's what I'm working on:
width, height := r.window.GetSize()
pixels := make([]byte, 3*width*height)
// Read the buffer into memory
var buf unsafe.Pointer
gl.PixelStorei(gl.UNPACK_ALIGNMENT, 1)
gl.ReadPixels(0, 0, int32(width), int32(height), gl.RGB, gl.UNSIGNED_BYTE, buf)
pixels = []byte(&buf) // <-- LINE 99
This triggers the following error during compile time:
videoenderer.go:99: cannot convert &buf (type *unsafe.Pointer) to type []byte.
How do I convert unsafe.Pointer
to a byte array?
Since unsafe.Pointer
is already a pointer, you can't use a pointer to unsafe.Pointer
, but you should use it directly. A simple example:
bytes := []byte{104, 101, 108, 108, 111}
p := unsafe.Pointer(&bytes)
str := *(*string)(p) //cast it to a string pointer and assign the value of this pointer
fmt.Println(str) //prints "hello"