callbacks.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package al
  2. /*
  3. #include <stdlib.h>
  4. #include <allegro5/allegro.h>
  5. #include "helpers.h"
  6. #include "callbacks.h"
  7. */
  8. import "C"
  9. import "unsafe"
  10. // Callback function for CreateCustomBitmap()
  11. type CreateCustomBitmapCallback func(bitmap *Bitmap, data interface{}) bool
  12. // Callback context for CreateCustomBitmap()
  13. type createCustomBitmapContext struct {
  14. fn CreateCustomBitmapCallback
  15. data interface{}
  16. }
  17. //export go_create_custom_bitmap_callback
  18. func go_create_custom_bitmap_callback(ptr unsafe.Pointer, context unsafe.Pointer) C.bool {
  19. ccbd := (*createCustomBitmapContext)(context)
  20. cbmp := (*C.ALLEGRO_BITMAP)(ptr)
  21. bmp := wrapBitmapRaw(cbmp)
  22. fptr := ccbd.fn
  23. return b2cb((fptr)(bmp, ccbd.data))
  24. }
  25. // Callback function for RunMain()
  26. type RunMainCallback func(args []string, data interface{}) int
  27. // Callback context for CreateCustomBitmap()
  28. type runMainContext struct {
  29. fn RunMainCallback
  30. data interface{}
  31. }
  32. var runMain runMainContext
  33. //export go_run_main_callback
  34. func go_run_main_callback(argc C.int, argv ** C.char) C.int {
  35. args := GoStrings(argc, argv)
  36. return C.int(runMain.fn(args, runMain.data))
  37. }
  38. // generic function pointer caller
  39. var CallbackInt func() int = nil
  40. //export go_generic_callback_int
  41. func go_generic_callback_int() int {
  42. if CallbackInt != nil {
  43. return CallbackInt()
  44. }
  45. return 0
  46. }
  47. type CallbackFunction func() int
  48. type callbackData struct {
  49. fn CallbackFunction
  50. data unsafe.Pointer
  51. }
  52. // the function below is the C callback that will be given to the
  53. // C api that needs a callback. It uses a callback context with a
  54. // Go function pointer in it to call that go function.
  55. //export go_take_callback_callback
  56. func go_take_callback_callback(context unsafe.Pointer) int {
  57. cbd := (*callbackData)(context)
  58. fn := cbd.fn
  59. return fn()
  60. }
  61. // Finally wrap the C callback caller function.
  62. func TakeCallback(fn CallbackFunction) int {
  63. ctx := unsafe.Pointer(&callbackData{fn, nil})
  64. return int(C.go_take_callback(ctx))
  65. }