doubaben7394
2019-02-27 17:48
浏览 172
已采纳

如何使用golang库中的回调函数?

I'm still relatively new to Go and I've decided to try some OpenGL since there exists a Go library which provides bindings for this. As part of setting up OpenGL I need to use the Go glfw library. I need to use the glfw library function SetFramebufferSizeCallback which requires an argument of type FrameBuffersizeCallback; so I essentially need to pass a function that matches that type's signature which I believe I have done. However, I keep getting the following error:

./main.go:43:35: cannot use fbCallback (type func(*glfw.Window, int32, int32)) as type glfw.FramebufferSizeCallback in argument to window.SetFramebufferSizeCallback

And I'm really not sure why this is happening. I've checked that my glfw version matches the documentation; I've checked the code for the implementation on github and my machine and it is all consistent. So I have no clue what I'm doing wrong. Here is my code, it shouldn't do anything interesting if built, but demonstrates the error:

package main

import (
    "github.com/go-gl/gl/v3.3-core/gl"
    "github.com/go-gl/glfw/v3.2/glfw"
    "log"
    "runtime"
)

func fbCallback(window *glfw.Window, width int32, height int32) {
    gl.Viewport(0, 0, width, height)
}

func init() {
    runtime.LockOSThread()
}

func main() {
    err := glfw.Init()
    if err != nil {
        panic(err)
    }

    defer glfw.Terminate()

    glfw.WindowHint(glfw.ContextVersionMajor, 3)
    glfw.WindowHint(glfw.ContextVersionMinor, 3)
    glfw.WindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)

    window, err := glfw.CreateWindow(640, 480, "Testing", nil, nil)

    if err != nil {
        panic(err)
    }

    window.MakeContextCurrent()

    if err := gl.Init(); err != nil {
        log.Fatalln(err)
    }

    gl.Viewport(0, 0, 800, 600)
    window.SetFramebufferSizeCallback(fbCallback) //Does not work
}

My understanding of how this should really work is demonstrated in the following short program which works. I'd be happy for someone to point out why this short example works and the above does not. I may have some holes in my understanding.

package main

import (
    "fmt"
)

type callback func(int, int) int

func sum(x int, y int) int {
    return x + y
}

func useCallback(cb callback) {
    result := cb(2, 3)
    fmt.Println(result)
}

func main() {
    useCallback(sum)
}
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题