Jes*_*nds 0 arrays opengl pointers type-conversion go
我正在尝试为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
Run Code Online (Sandbox Code Playgroud)
这会在编译期间触发以下错误:
video\renderer.go:99: cannot convert &buf (type *unsafe.Pointer) to type []byte.
Run Code Online (Sandbox Code Playgroud)
如何转换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"
Run Code Online (Sandbox Code Playgroud)