seq_darwin.go.support 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // Copyright 2016 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package main
  5. // Go support functions for Objective-C. Note that this
  6. // file is copied into and compiled with the generated
  7. // bindings.
  8. /*
  9. #cgo CFLAGS: -x objective-c -fobjc-arc -fmodules -fblocks -Werror
  10. #cgo LDFLAGS: -framework Foundation
  11. #include <stdint.h>
  12. #include <stdlib.h>
  13. #include "seq.h"
  14. */
  15. import "C"
  16. import (
  17. "unsafe"
  18. "golang.org/x/mobile/bind/seq"
  19. )
  20. // DestroyRef is called by Objective-C to inform Go it is done with a reference.
  21. //export DestroyRef
  22. func DestroyRef(refnum C.int32_t) {
  23. seq.Delete(int32(refnum))
  24. }
  25. // encodeString copies a Go string and returns it as a nstring.
  26. func encodeString(s string) C.nstring {
  27. n := C.int(len(s))
  28. if n == 0 {
  29. return C.nstring{}
  30. }
  31. ptr := C.malloc(C.size_t(n))
  32. if ptr == nil {
  33. panic("encodeString: malloc failed")
  34. }
  35. copy((*[1<<31 - 1]byte)(ptr)[:n], s)
  36. return C.nstring{ptr: ptr, len: n}
  37. }
  38. // decodeString converts a nstring to a Go string. The
  39. // data in str is freed after use.
  40. func decodeString(str C.nstring) string {
  41. if str.ptr == nil {
  42. return ""
  43. }
  44. s := C.GoStringN((*C.char)(str.ptr), str.len)
  45. C.free(str.ptr)
  46. return s
  47. }
  48. // fromSlice converts a slice to a nbyteslice.
  49. // If cpy is set, a malloc'ed copy of the data is returned.
  50. func fromSlice(s []byte, cpy bool) C.nbyteslice {
  51. if s == nil || len(s) == 0 {
  52. return C.nbyteslice{}
  53. }
  54. ptr, n := unsafe.Pointer(&s[0]), C.int(len(s))
  55. if cpy {
  56. nptr := C.malloc(C.size_t(n))
  57. if nptr == nil {
  58. panic("fromSlice: malloc failed")
  59. }
  60. copy((*[1<<31 - 1]byte)(nptr)[:n], (*[1<<31 - 1]byte)(ptr)[:n])
  61. ptr = nptr
  62. }
  63. return C.nbyteslice{ptr: ptr, len: n}
  64. }
  65. // toSlice takes a nbyteslice and returns a byte slice with the data. If cpy is
  66. // set, the slice contains a copy of the data. If not, the generated Go code
  67. // calls releaseByteSlice after use.
  68. func toSlice(s C.nbyteslice, cpy bool) []byte {
  69. if s.ptr == nil || s.len == 0 {
  70. return nil
  71. }
  72. var b []byte
  73. if cpy {
  74. b = C.GoBytes(s.ptr, C.int(s.len))
  75. C.free(s.ptr)
  76. } else {
  77. b = (*[1<<31 - 1]byte)(unsafe.Pointer(s.ptr))[:s.len:s.len]
  78. }
  79. return b
  80. }