2014-12-04 51 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