在SDL Go程序中复制纹理时运行时出现混乱

时间:2014-08-15 10:54:27

标签: go sdl sdl-2

我有一个SDL2 go程序,试图将像素阵列写入屏幕。当我尝试使用新像素更新纹理时,程序会出现运行时错误:

fatal error: unexpected signal during runtime execution

不幸的是我几乎找不到关于如何在Go中传递不安全指针的文档,我不确定我是否正确接近这个,这里有一些示例代码可以解决这个问题:

func main() {
    window := sdl.CreateWindow("test", sdl.WINDOWPOS_UNDEFINED, sdl.WINDOWPOS_UNDEFINED,
        800, 600, sdl.WINDOW_SHOWN)
    renderer := sdl.CreateRenderer(window, -1, 0)
    texture := sdl.CreateTexture(renderer, sdl.PIXELFORMAT_ARGB8888,
        sdl.TEXTUREACCESS_STATIC, 800, 600)

    defer renderer.Destroy()
    defer texture.Destroy()
    defer window.Destroy()

    for {
        pixels := make([]uint32, 800*600)

        texture.Update(nil, unsafe.Pointer(&pixels), int(800*unsafe.Sizeof(pixels)))
        window.UpdateSurface()

        renderer.Clear()
        renderer.Copy(texture, nil, nil)
        renderer.Present()
    }

    sdl.Delay(1000)
    sdl.Quit()
}

此代码将在没有错误的情况下进行编译,但在运行时会产生运行时混乱,但我无法看到导致此代码的原因。

我正在使用这些SDL2 Go绑定:https://github.com/veandco/go-sdl2

1 个答案:

答案 0 :(得分:1)

pitch参数尽可能地预期表面的宽度* sizeof(int32),此代码在每个循环中工作并打印随机像素:

func main() {
    window, err := sdl.CreateWindow("test", sdl.WINDOWPOS_UNDEFINED,
        sdl.WINDOWPOS_UNDEFINED, 800, 600, sdl.WINDOW_SHOWN)
    if err != nil {
        log.Fatal(err)
    }
    defer window.Destroy()

    renderer, err := sdl.CreateRenderer(window, -1, 0)
    if err != nil {
        log.Fatal(err)
    }
    defer renderer.Destroy()

    texture, err := renderer.CreateTexture(sdl.PIXELFORMAT_ARGB8888,
        sdl.TEXTUREACCESS_STATIC, 800, 600)

    if err != nil {
        log.Fatal(err)
    }
    defer texture.Destroy()

    pixels := make([]uint32, 800*600)
L:
    for {
        for event := sdl.PollEvent(); event != nil; event = sdl.PollEvent() {
            if _, ok := event.(*sdl.QuitEvent); ok {
                break L
            }
        }
        for i := range pixels {
            pixels[i] = 0x00777777 + uint32(rand.Intn(0x00AAAAAA))
        }
        //4 == sizeof(int32), unsafe.Sizeof(pixels) returns the actual size of
        //the slice header which is 24
        texture.Update(nil, unsafe.Pointer(&pixels[0]), 800*4)
        window.UpdateSurface()

        renderer.Clear()
        renderer.Copy(texture, nil, nil)
        renderer.Present()
    }

    sdl.Delay(1000)
    sdl.Quit()
}

//编辑它应该是unsafe.Pointer(&pixels[0])而不是unsafe.Pointer(&pixels)