2014-12-04 49 views
0
字节

我试图写在走我的OpenGL项目中的截图功能,我使用了OpenGL绑定这里找到:unsafe.Pointer为[]围棋

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

回答

4

由于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" 
+0

谢谢,这有帮助。我可以问为什么它必须写成'*(* []字节)'这是什么意思?指针转换为指向字节数组的指针?那么它是如何变成[]字节的? – 2014-12-04 14:02:14

+0

它很混乱,来自C:'(* string)(p)'表示“将p转换为字符串指针”。它之前的额外'*'表示“该指针的值”。所以基本上这行代码是这样写的:'let'str'是一个字符串指针p的值。 – 2014-12-04 14:27:35

+5

为了C-interop的目的,'unsafe.Pointer(&bytes)'会创建一个指向第一个字节的指针slice,它不是* data *的第一个字节(这通常是C期望的) - 因此,您应该使用'unsafe.Pointer(&bytes [0])'(当然,您需要确保你有第零个元素)。 – weberc2 2014-12-04 17:54:47