我正在尝试用 Go 为我的 OpenGL 项目编写屏幕截图函数,我正在使用此处找到的 OpenGL 绑定(bind):
这是我用来制作屏幕截图的代码,或者说,这就是我正在处理的代码:
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
这会在编译期间触发以下错误:
video\renderer.go:99: cannot convert &buf (type *unsafe.Pointer) to type []byte.
如何将 unsafe.Pointer
转换为字节数组?
最佳答案
因为unsafe.Pointer
已经是一个指针,你不能使用指向unsafe.Pointer
的指针,但是你应该直接使用它。一个简单的例子:
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"
关于arrays - unsafe.Pointer to []byte in Go,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27295184/