arrays - unsafe.Pointer to []byte in Go

标签 arrays pointers opengl go type-conversion

我正在尝试用 Go 为我的 OpenGL 项目编写屏幕截图函数,我正在使用此处找到的 OpenGL 绑定(bind):

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

这会在编译期间触发以下错误:

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/

相关文章:

c - 使用 `const` 中断程序

ios - 数组数据插入

c - 向数组中插入一个值,并根据值c排列数组

php - 用 mysql 数组填充 php 表单字段(点击)

javascript - 混合字母和数字内容的数组排序在 Firefox 中不起作用

function - 改变值(value)

c++ - 将(n 个第一个字节的)unsigned char 指针转换为 float 和 double C++

c++ - 丢失指针值

c++ - 设置 VisualC++ 以使用 OpenGL 4.1?

c++ - OpenGL - 透视问题