drzrdc1766788 2014-12-04 13:24
浏览 213
已采纳

不安全。在Go中指向[] byte的指针

I'm trying to write a screenshot function for my OpenGL project in Go, I'm using the OpenGL bindings found here:

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

This is the code I use to make a screenshot, or well, it's what I'm working on:

    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

This triggers the following error during compile time:

videoenderer.go:99: cannot convert &buf (type *unsafe.Pointer) to type []byte.

How do I convert unsafe.Pointer to a byte array?

  • 写回答

1条回答 默认 最新

  • duanlijia5864 2014-12-04 13:55
    关注

    Since unsafe.Pointer is already a pointer, you can't use a pointer to unsafe.Pointer, but you should use it directly. A simple example:

    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"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应