unsafe.Pointer到Go中的[]字节

Jes*_*nds 0 arrays opengl pointers type-conversion go

我正在尝试为Go中的OpenGL项目编写一个截图函数,我正在使用此处的OpenGL绑定:

https://github.com/go-gl/glow

这是我用来制作屏幕截图的代码,或者说,这就是我正在做的事情:

    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为字节数组?

Not*_*fer 7

由于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)

  • 出于C-interop的目的,`unsafe.Pointer(&bytes)`将创建一个指向切片的第一个字节的指针,该指针不是*data*的第一个字节(通常是C期望的) - 对于这个原因,你应该使用`unsafe.Pointer(&bytes [0])`(当然,你需要确保你有第0个元素). (7认同)
  • @weberc2 非常小心,这是一个非常讨厌的黑客。[]byte 类型是一个切片结构,由三个字段组成:ptr、len 和 capa。字符串结构体有两个字段:ptr 和 len。从 []byte 到 string *发生* 的转换是兼容的,导致 string 反映字节并忽略容量。如果您修改字符串也会更改的字节,则会破坏不变性保证。见 https://play.golang.org/p/ye9UJts1Zoe (2认同)