我正在尝试用Go为我的OpenGL项目编写一个屏幕截图函数,我正在使用这里提供的OpenGL绑定:
这是我用来制作屏幕截图的代码,或者,这就是我正在做的:
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转换为字节数组?
发布于 2014-12-04 21:55:12
因为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"发布于 2021-08-19 16:38:18
如何将
unsafe.Pointer转换为字节数组?
这可能是XY问题。根据我所看到的,您不需要将unsafe.Pointer转换为字节数组/片。
问题的根源在于您试图向gl.ReadPixels传递buf。我不熟悉go-gl包,但看起来您应该使用gl.Ptr(data interface{})将unsafe.Pointer传递给现有的buffer (我假设这就是pixels ):
width, height := r.window.GetSize()
pixels := make([]byte, 3*width*height)
// ...
buf := gl.Ptr(&pixels[0]) // unsafe.Pointer pointing to 1st element in pixels
gl.ReadPixels(0, 0, int32(width), int32(height), gl.RGB, gl.UNSIGNED_BYTE, buf)
// Also could try (I believe this requires OpenGL 4.5):
gl.ReadPixels(0, 0, int32(width), int32(height), gl.RGB, gl.UNSIGNED_BYTE, int32(len(pixels)), buf)
// Access pixels as normal, no need for conversion.也就是说,可以从unsafe.Pointer转到字节片/数组,再回到字节数组/片。为了避免冗余,我建议查看现有的SO问题:How to create an array or a slice from an array unsafe.Pointer in golang?。
不过,长话短说,如果您可以访问Go 1.17,您可以简单地执行以下操作来获得[]byte切片。
pixels = unsafe.Slice((*byte)(buf), desiredSliceLen)https://stackoverflow.com/questions/27295184
复制相似问题