aid.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package al
  2. /*
  3. #include <stdlib.h>
  4. */
  5. import "C"
  6. import "unsafe"
  7. import "runtime"
  8. import "fmt"
  9. // Helper functions for working with C easier
  10. // Calls C malloc
  11. func malloc(size int) unsafe.Pointer {
  12. return (unsafe.Pointer(C.calloc(C.size_t(size), C.size_t(1))))
  13. }
  14. // Calls C free
  15. func free(ptr unsafe.Pointer) {
  16. C.free(ptr)
  17. }
  18. // Allocates a string with the given byte length
  19. // don't forget a call to defer cstrFree() !
  20. func cstrNew(size int) *C.char {
  21. return (*C.char)(malloc(size))
  22. }
  23. // free is a method on C char * strings to method to free the associated memory
  24. func cstrFree(self *C.char) {
  25. free(unsafe.Pointer(self))
  26. }
  27. // Coverts a string to a C string. This allocates memory,
  28. // so don't forget to add a "defer cstrFree(cstr)"
  29. func cstr(self string) *C.char {
  30. return C.CString(self)
  31. }
  32. // Shorthand for C.GoString. Yes, it's just laziness. :)
  33. func gostr(cstr *C.char) string {
  34. return C.GoString(cstr)
  35. }
  36. // Converts an int pointer to a C.int pointer.
  37. func cintptr(ptr *int) *C.int {
  38. return (*C.int)(unsafe.Pointer(ptr))
  39. }
  40. /*
  41. // Converts a byte pointer to a C.Uchar8 pointer.
  42. func cbyteptr(ptr * uint8) (*C.Uint8) {
  43. return (*C.Uint8)(unsafe.Pointer(ptr))
  44. }
  45. */
  46. // Converts ints to bools.
  47. func i2b(res int) bool {
  48. if res != 0 {
  49. return true
  50. }
  51. return false
  52. }
  53. // Converts bools to ints.
  54. func b2i(res bool) int {
  55. if res {
  56. return 1
  57. }
  58. return 0
  59. }
  60. // Interface for destructable objects
  61. type Destroyer interface {
  62. Destroy()
  63. }
  64. // Sets up a automatic finalizer for destructable objects
  65. // that will call Destroy using runtime.SetFinalizer
  66. // when the garbage collecter cleans up self.
  67. // self may also be nil in which case the destructor is NOT set up
  68. func SelfDestruct(self Destroyer) {
  69. if self == nil {
  70. return
  71. }
  72. clean := func(me Destroyer) {
  73. fmt.Printf("Finalizing %#v.\n", me)
  74. me.Destroy()
  75. }
  76. runtime.SetFinalizer(self, clean)
  77. }