簡體   English   中英

unsafe.Pointer 指向 Go 中的 []byte

[英]unsafe.Pointer to []byte in Go

我正在嘗試為 Go 中的 OpenGL 項目編寫屏幕截圖 function,我正在使用此處找到的 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

這會在編譯期間觸發以下錯誤:

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"

如何將unsafe.Pointer轉換為字節數組?

這可能是一個 XY 問題。 從我所見,您實際上並不需要將unsafe.Pointer轉換為字節數組/切片。

問題的根源在於您試圖將buf傳遞給gl.ReadPixels 我不熟悉go-gl package,但看起來您應該使用gl.Ptr(data interface{})unsafe.Pointer傳遞給現有緩沖區(我假設pixels是什么):

    width, height := r.window.GetSize()
    pixels := make([]byte, 3*width*height)

    // ...

    buf := gl.Ptr(&pixels[0]) // unsafe.Pointer pointing to 1st element in pixels
    gl.ReadPixels(0, 0, int32(width), int32(height), gl.RGB, gl.UNSIGNED_BYTE, buf)
    // Also could try (I believe this requires OpenGL 4.5):
    gl.ReadPixels(0, 0, int32(width), int32(height), gl.RGB, gl.UNSIGNED_BYTE, int32(len(pixels)), buf)
    // Access pixels as normal, no need for conversion.

也就是說,可以將 go 從unsafe.Pointer指向字節切片/數組返回到字節數組/切片。 為了避免冗余,我建議查看這個現有的 SO 問題: How to create an array or a slice from an array unsafe.Pointer in golang? .

不過,長話短說,如果您可以訪問 Go 1.17,您只需執行以下操作即可獲得[]byte切片。

pixels = unsafe.Slice((*byte)(buf), desiredSliceLen)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM