objc_runtime_darwin.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. // SPDX-License-Identifier: Apache-2.0
  2. // SPDX-FileCopyrightText: 2022 The Ebitengine Authors
  3. // Package objc is a low-level pure Go objective-c runtime. This package is easy to use incorrectly, so it is best
  4. // to use a wrapper that provides the functionality you need in a safer way.
  5. package objc
  6. import (
  7. "errors"
  8. "fmt"
  9. "math"
  10. "reflect"
  11. "regexp"
  12. "runtime"
  13. "unicode"
  14. "unsafe"
  15. "github.com/ebitengine/purego"
  16. )
  17. // TODO: support try/catch?
  18. // https://stackoverflow.com/questions/7062599/example-of-how-objective-cs-try-catch-implementation-is-executed-at-runtime
  19. var (
  20. objc_msgSend_fn uintptr
  21. objc_msgSend_stret_fn uintptr
  22. objc_msgSend func(obj ID, cmd SEL, args ...interface{}) ID
  23. objc_msgSendSuper2_fn uintptr
  24. objc_msgSendSuper2_stret_fn uintptr
  25. objc_msgSendSuper2 func(super *objc_super, cmd SEL, args ...interface{}) ID
  26. objc_getClass func(name string) Class
  27. objc_getProtocol func(name string) *Protocol
  28. objc_allocateClassPair func(super Class, name string, extraBytes uintptr) Class
  29. objc_registerClassPair func(class Class)
  30. sel_registerName func(name string) SEL
  31. class_getSuperclass func(class Class) Class
  32. class_getInstanceVariable func(class Class, name string) Ivar
  33. class_getInstanceSize func(class Class) uintptr
  34. class_addMethod func(class Class, name SEL, imp IMP, types string) bool
  35. class_addIvar func(class Class, name string, size uintptr, alignment uint8, types string) bool
  36. class_addProtocol func(class Class, protocol *Protocol) bool
  37. ivar_getOffset func(ivar Ivar) uintptr
  38. ivar_getName func(ivar Ivar) string
  39. object_getClass func(obj ID) Class
  40. object_getIvar func(obj ID, ivar Ivar) ID
  41. object_setIvar func(obj ID, ivar Ivar, value ID)
  42. protocol_getName func(protocol *Protocol) string
  43. protocol_isEqual func(p *Protocol, p2 *Protocol) bool
  44. )
  45. func init() {
  46. objc, err := purego.Dlopen("/usr/lib/libobjc.A.dylib", purego.RTLD_GLOBAL)
  47. if err != nil {
  48. panic(fmt.Errorf("objc: %w", err))
  49. }
  50. objc_msgSend_fn, err = purego.Dlsym(objc, "objc_msgSend")
  51. if err != nil {
  52. panic(fmt.Errorf("objc: %w", err))
  53. }
  54. if runtime.GOARCH == "amd64" {
  55. objc_msgSend_stret_fn, err = purego.Dlsym(objc, "objc_msgSend_stret")
  56. if err != nil {
  57. panic(fmt.Errorf("objc: %w", err))
  58. }
  59. objc_msgSendSuper2_stret_fn, err = purego.Dlsym(objc, "objc_msgSendSuper2_stret")
  60. if err != nil {
  61. panic(fmt.Errorf("objc: %w", err))
  62. }
  63. }
  64. purego.RegisterFunc(&objc_msgSend, objc_msgSend_fn)
  65. objc_msgSendSuper2_fn, err = purego.Dlsym(objc, "objc_msgSendSuper2")
  66. if err != nil {
  67. panic(fmt.Errorf("objc: %w", err))
  68. }
  69. purego.RegisterFunc(&objc_msgSendSuper2, objc_msgSendSuper2_fn)
  70. purego.RegisterLibFunc(&object_getClass, objc, "object_getClass")
  71. purego.RegisterLibFunc(&objc_getClass, objc, "objc_getClass")
  72. purego.RegisterLibFunc(&objc_getProtocol, objc, "objc_getProtocol")
  73. purego.RegisterLibFunc(&objc_allocateClassPair, objc, "objc_allocateClassPair")
  74. purego.RegisterLibFunc(&objc_registerClassPair, objc, "objc_registerClassPair")
  75. purego.RegisterLibFunc(&sel_registerName, objc, "sel_registerName")
  76. purego.RegisterLibFunc(&class_getSuperclass, objc, "class_getSuperclass")
  77. purego.RegisterLibFunc(&class_getInstanceVariable, objc, "class_getInstanceVariable")
  78. purego.RegisterLibFunc(&class_addMethod, objc, "class_addMethod")
  79. purego.RegisterLibFunc(&class_addIvar, objc, "class_addIvar")
  80. purego.RegisterLibFunc(&class_addProtocol, objc, "class_addProtocol")
  81. purego.RegisterLibFunc(&class_getInstanceSize, objc, "class_getInstanceSize")
  82. purego.RegisterLibFunc(&ivar_getOffset, objc, "ivar_getOffset")
  83. purego.RegisterLibFunc(&ivar_getName, objc, "ivar_getName")
  84. purego.RegisterLibFunc(&protocol_getName, objc, "protocol_getName")
  85. purego.RegisterLibFunc(&protocol_isEqual, objc, "protocol_isEqual")
  86. purego.RegisterLibFunc(&object_getIvar, objc, "object_getIvar")
  87. purego.RegisterLibFunc(&object_setIvar, objc, "object_setIvar")
  88. }
  89. // ID is an opaque pointer to some Objective-C object
  90. type ID uintptr
  91. // Class returns the class of the object.
  92. func (id ID) Class() Class {
  93. return object_getClass(id)
  94. }
  95. // Send is a convenience method for sending messages to objects. This function takes a SEL
  96. // instead of a string since RegisterName grabs the global Objective-C lock. It is best to cache the result
  97. // of RegisterName.
  98. func (id ID) Send(sel SEL, args ...interface{}) ID {
  99. return objc_msgSend(id, sel, args...)
  100. }
  101. // GetIvar reads the value of an instance variable in an object.
  102. func (id ID) GetIvar(ivar Ivar) ID {
  103. return object_getIvar(id, ivar)
  104. }
  105. // SetIvar sets the value of an instance variable in an object.
  106. func (id ID) SetIvar(ivar Ivar, value ID) {
  107. object_setIvar(id, ivar, value)
  108. }
  109. // keep in sync with func.go
  110. const maxRegAllocStructSize = 16
  111. // Send is a convenience method for sending messages to objects that can return any type.
  112. // This function takes a SEL instead of a string since RegisterName grabs the global Objective-C lock.
  113. // It is best to cache the result of RegisterName.
  114. func Send[T any](id ID, sel SEL, args ...any) T {
  115. var fn func(id ID, sel SEL, args ...any) T
  116. var zero T
  117. if runtime.GOARCH == "amd64" &&
  118. reflect.ValueOf(zero).Kind() == reflect.Struct &&
  119. reflect.ValueOf(zero).Type().Size() > maxRegAllocStructSize {
  120. purego.RegisterFunc(&fn, objc_msgSend_stret_fn)
  121. } else {
  122. purego.RegisterFunc(&fn, objc_msgSend_fn)
  123. }
  124. return fn(id, sel, args...)
  125. }
  126. // objc_super data structure is generated by the Objective-C compiler when it encounters the super keyword
  127. // as the receiver of a message. It specifies the class definition of the particular superclass that should
  128. // be messaged.
  129. type objc_super struct {
  130. receiver ID
  131. superClass Class
  132. }
  133. // SendSuper is a convenience method for sending message to object's super. This function takes a SEL
  134. // instead of a string since RegisterName grabs the global Objective-C lock. It is best to cache the result
  135. // of RegisterName.
  136. func (id ID) SendSuper(sel SEL, args ...interface{}) ID {
  137. super := &objc_super{
  138. receiver: id,
  139. superClass: id.Class(),
  140. }
  141. return objc_msgSendSuper2(super, sel, args...)
  142. }
  143. // SendSuper is a convenience method for sending message to object's super that can return any type.
  144. // This function takes a SEL instead of a string since RegisterName grabs the global Objective-C lock.
  145. // It is best to cache the result of RegisterName.
  146. func SendSuper[T any](id ID, sel SEL, args ...any) T {
  147. super := &objc_super{
  148. receiver: id,
  149. superClass: id.Class(),
  150. }
  151. var fn func(objcSuper *objc_super, sel SEL, args ...any) T
  152. var zero T
  153. if runtime.GOARCH == "amd64" &&
  154. reflect.ValueOf(zero).Kind() == reflect.Struct &&
  155. reflect.ValueOf(zero).Type().Size() > maxRegAllocStructSize {
  156. purego.RegisterFunc(&fn, objc_msgSendSuper2_stret_fn)
  157. } else {
  158. purego.RegisterFunc(&fn, objc_msgSendSuper2_fn)
  159. }
  160. return fn(super, sel, args...)
  161. }
  162. // SEL is an opaque type that represents a method selector
  163. type SEL uintptr
  164. // RegisterName registers a method with the Objective-C runtime system, maps the method name to a selector,
  165. // and returns the selector value. This function grabs the global Objective-c lock. It is best the cache the
  166. // result of this function.
  167. func RegisterName(name string) SEL {
  168. return sel_registerName(name)
  169. }
  170. // Class is an opaque type that represents an Objective-C class.
  171. type Class uintptr
  172. // GetClass returns the Class object for the named class, or nil if the class is not registered with the Objective-C runtime.
  173. func GetClass(name string) Class {
  174. return objc_getClass(name)
  175. }
  176. // MethodDef represents the Go function and the selector that ObjC uses to access that function.
  177. type MethodDef struct {
  178. Cmd SEL
  179. Fn any
  180. }
  181. // IvarAttrib is the attribute that an ivar has. It affects if and which methods are automatically
  182. // generated when creating a class with RegisterClass. See [Apple Docs] for an understanding of these attributes.
  183. // The fields are still accessible using objc.GetIvar and objc.SetIvar regardless of the value of IvarAttrib.
  184. //
  185. // Take for example this Objective-C code:
  186. //
  187. // @property (readwrite) float value;
  188. //
  189. // In Go, the functions can be accessed as followed:
  190. //
  191. // var value = purego.Send[float32](id, purego.RegisterName("value"))
  192. // id.Send(purego.RegisterName("setValue:"), 3.46)
  193. //
  194. // [Apple Docs]: https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProperties.html
  195. type IvarAttrib int
  196. const (
  197. ReadOnly IvarAttrib = 1 << iota
  198. ReadWrite
  199. )
  200. // FieldDef is a definition of a field to add to an Objective-C class.
  201. // The name of the field is what will be used to access it through the Ivar. If the type is bool
  202. // the name cannot start with `is` since a getter will be generated with the name `isBoolName`.
  203. // The name also cannot contain any spaces.
  204. // The type is the Go equivalent type of the Ivar.
  205. // Attribute determines if a getter and or setter method is generated for this field.
  206. type FieldDef struct {
  207. Name string
  208. Type reflect.Type
  209. Attribute IvarAttrib
  210. }
  211. // ivarRegex checks to make sure the Ivar is correctly formatted
  212. var ivarRegex = regexp.MustCompile("[a-z_][a-zA-Z0-9_]*")
  213. // RegisterClass takes the name of the class to create, the superclass, a list of protocols this class
  214. // implements, a list of fields this class has and a list of methods. It returns the created class or an error
  215. // describing what went wrong.
  216. func RegisterClass(name string, superClass Class, protocols []*Protocol, ivars []FieldDef, methods []MethodDef) (Class, error) {
  217. class := objc_allocateClassPair(superClass, name, 0)
  218. if class == 0 {
  219. return 0, fmt.Errorf("objc: failed to create class with name '%s'", name)
  220. }
  221. // Add Protocols
  222. for _, p := range protocols {
  223. if !class.AddProtocol(p) {
  224. return 0, fmt.Errorf("objc: couldn't add Protocol %s", protocol_getName(p))
  225. }
  226. }
  227. // Add exported methods based on the selectors returned from ClassDef(string) SEL
  228. for idx, def := range methods {
  229. imp, err := func() (imp IMP, err error) {
  230. defer func() {
  231. if r := recover(); r != nil {
  232. err = fmt.Errorf("objc: failed to create IMP: %s", r)
  233. }
  234. }()
  235. return NewIMP(def.Fn), nil
  236. }()
  237. if err != nil {
  238. return 0, fmt.Errorf("objc: couldn't add Method at index %d: %w", idx, err)
  239. }
  240. encoding, err := encodeFunc(def.Fn)
  241. if err != nil {
  242. return 0, fmt.Errorf("objc: couldn't add Method at index %d: %w", idx, err)
  243. }
  244. if !class.AddMethod(def.Cmd, imp, encoding) {
  245. return 0, fmt.Errorf("objc: couldn't add Method at index %d", idx)
  246. }
  247. }
  248. // Add Ivars
  249. for _, instVar := range ivars {
  250. ivar := instVar
  251. if !ivarRegex.MatchString(ivar.Name) {
  252. return 0, fmt.Errorf("objc: Ivar must start with a lowercase letter and only contain ASCII letters and numbers: '%s'", ivar.Name)
  253. }
  254. size := ivar.Type.Size()
  255. alignment := uint8(math.Log2(float64(ivar.Type.Align())))
  256. enc, err := encodeType(ivar.Type, false)
  257. if err != nil {
  258. return 0, fmt.Errorf("objc: couldn't add Ivar %s: %w", ivar.Name, err)
  259. }
  260. if !class_addIvar(class, ivar.Name, size, alignment, enc) {
  261. return 0, fmt.Errorf("objc: couldn't add Ivar %s", ivar.Name)
  262. }
  263. offset := class.InstanceVariable(ivar.Name).Offset()
  264. switch ivar.Attribute {
  265. case ReadWrite:
  266. ty := reflect.FuncOf(
  267. []reflect.Type{
  268. reflect.TypeOf(ID(0)), reflect.TypeOf(SEL(0)), ivar.Type,
  269. },
  270. nil, false,
  271. )
  272. var encoding string
  273. if encoding, err = encodeFunc(reflect.New(ty).Elem().Interface()); err != nil {
  274. return 0, fmt.Errorf("objc: failed to create read method for '%s': %w", ivar.Name, err)
  275. }
  276. val := reflect.MakeFunc(ty, func(args []reflect.Value) (results []reflect.Value) {
  277. // on entry the first and second arguments are ID and SEL followed by the value
  278. if len(args) != 3 {
  279. panic(fmt.Sprintf("objc: incorrect number of args. expected 3 got %d", len(args)))
  280. }
  281. // The following reflect code does the equivalent of this:
  282. //
  283. // ((*struct {
  284. // Padding [offset]byte
  285. // Value int
  286. // })(unsafe.Pointer(args[0].Interface().(ID)))).v = 123
  287. //
  288. // However, since the type of the variable is unknown reflection is used to actually assign the value
  289. id := args[0].Interface().(ID)
  290. ptr := *(*unsafe.Pointer)(unsafe.Pointer(&id)) // circumvent go vet
  291. reflect.NewAt(ivar.Type, unsafe.Add(ptr, offset)).Elem().Set(args[2])
  292. return nil
  293. }).Interface()
  294. // this code only works for ascii but that shouldn't be a problem
  295. selector := "set" + string(unicode.ToUpper(rune(ivar.Name[0]))) + ivar.Name[1:] + ":\x00"
  296. class.AddMethod(RegisterName(selector), NewIMP(val), encoding)
  297. fallthrough // also implement the read method
  298. case ReadOnly:
  299. ty := reflect.FuncOf(
  300. []reflect.Type{
  301. reflect.TypeOf(ID(0)), reflect.TypeOf(SEL(0)),
  302. },
  303. []reflect.Type{ivar.Type}, false,
  304. )
  305. var encoding string
  306. if encoding, err = encodeFunc(reflect.New(ty).Elem().Interface()); err != nil {
  307. return 0, fmt.Errorf("objc: failed to create read method for '%s': %w", ivar.Name, err)
  308. }
  309. val := reflect.MakeFunc(ty, func(args []reflect.Value) (results []reflect.Value) {
  310. // on entry the first and second arguments are ID and SEL
  311. if len(args) != 2 {
  312. panic(fmt.Sprintf("objc: incorrect number of args. expected 2 got %d", len(args)))
  313. }
  314. id := args[0].Interface().(ID)
  315. ptr := *(*unsafe.Pointer)(unsafe.Pointer(&id)) // circumvent go vet
  316. // the variable is located at an offset from the id
  317. return []reflect.Value{reflect.NewAt(ivar.Type, unsafe.Add(ptr, offset)).Elem()}
  318. }).Interface()
  319. if ivar.Type.Kind() == reflect.Bool {
  320. // this code only works for ascii but that shouldn't be a problem
  321. ivar.Name = "is" + string(unicode.ToUpper(rune(ivar.Name[0]))) + ivar.Name[1:]
  322. }
  323. class.AddMethod(RegisterName(ivar.Name), NewIMP(val), encoding)
  324. default:
  325. return 0, fmt.Errorf("objc: unknown Ivar Attribute (%d)", ivar.Attribute)
  326. }
  327. }
  328. objc_registerClassPair(class)
  329. return class, nil
  330. }
  331. const (
  332. encId = "@"
  333. encClass = "#"
  334. encSelector = ":"
  335. encChar = "c"
  336. encUChar = "C"
  337. encShort = "s"
  338. encUShort = "S"
  339. encInt = "i"
  340. encUInt = "I"
  341. encLong = "l"
  342. encULong = "L"
  343. encFloat = "f"
  344. encDouble = "d"
  345. encBool = "B"
  346. encVoid = "v"
  347. encPtr = "^"
  348. encCharPtr = "*"
  349. encStructBegin = "{"
  350. encStructEnd = "}"
  351. encUnsafePtr = "^v"
  352. )
  353. // encodeType returns a string representing a type as if it was given to @encode(typ)
  354. // Source: https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html#//apple_ref/doc/uid/TP40008048-CH100
  355. func encodeType(typ reflect.Type, insidePtr bool) (string, error) {
  356. switch typ {
  357. case reflect.TypeOf(Class(0)):
  358. return encClass, nil
  359. case reflect.TypeOf(ID(0)):
  360. return encId, nil
  361. case reflect.TypeOf(SEL(0)):
  362. return encSelector, nil
  363. }
  364. kind := typ.Kind()
  365. switch kind {
  366. case reflect.Bool:
  367. return encBool, nil
  368. case reflect.Int:
  369. return encLong, nil
  370. case reflect.Int8:
  371. return encChar, nil
  372. case reflect.Int16:
  373. return encShort, nil
  374. case reflect.Int32:
  375. return encInt, nil
  376. case reflect.Int64:
  377. return encULong, nil
  378. case reflect.Uint:
  379. return encULong, nil
  380. case reflect.Uint8:
  381. return encUChar, nil
  382. case reflect.Uint16:
  383. return encUShort, nil
  384. case reflect.Uint32:
  385. return encUInt, nil
  386. case reflect.Uint64:
  387. return encULong, nil
  388. case reflect.Uintptr:
  389. return encPtr, nil
  390. case reflect.Float32:
  391. return encFloat, nil
  392. case reflect.Float64:
  393. return encDouble, nil
  394. case reflect.Ptr:
  395. enc, err := encodeType(typ.Elem(), true)
  396. return encPtr + enc, err
  397. case reflect.Struct:
  398. if insidePtr {
  399. return encStructBegin + typ.Name() + encStructEnd, nil
  400. }
  401. encoding := encStructBegin
  402. encoding += typ.Name()
  403. encoding += "="
  404. for i := 0; i < typ.NumField(); i++ {
  405. f := typ.Field(i)
  406. tmp, err := encodeType(f.Type, false)
  407. if err != nil {
  408. return "", err
  409. }
  410. encoding += tmp
  411. }
  412. encoding = encStructEnd
  413. return encoding, nil
  414. case reflect.UnsafePointer:
  415. return encUnsafePtr, nil
  416. case reflect.String:
  417. return encCharPtr, nil
  418. }
  419. return "", errors.New(fmt.Sprintf("unhandled/invalid kind %v typed %v", kind, typ))
  420. }
  421. // encodeFunc returns a functions type as if it was given to @encode(fn)
  422. func encodeFunc(fn interface{}) (string, error) {
  423. typ := reflect.TypeOf(fn)
  424. if typ.Kind() != reflect.Func {
  425. return "", errors.New("not a func")
  426. }
  427. encoding := ""
  428. switch typ.NumOut() {
  429. case 0:
  430. encoding += encVoid
  431. case 1:
  432. tmp, err := encodeType(typ.Out(0), false)
  433. if err != nil {
  434. return "", err
  435. }
  436. encoding += tmp
  437. default:
  438. return "", errors.New("too many output parameters")
  439. }
  440. if typ.NumIn() < 2 {
  441. return "", errors.New("func doesn't take ID and SEL as its first two parameters")
  442. }
  443. encoding += encId
  444. for i := 1; i < typ.NumIn(); i++ {
  445. tmp, err := encodeType(typ.In(i), false)
  446. if err != nil {
  447. return "", err
  448. }
  449. encoding += tmp
  450. }
  451. return encoding, nil
  452. }
  453. // SuperClass returns the superclass of a class.
  454. // You should usually use NSObject‘s superclass method instead of this function.
  455. func (c Class) SuperClass() Class {
  456. return class_getSuperclass(c)
  457. }
  458. // AddMethod adds a new method to a class with a given name and implementation.
  459. // The types argument is a string containing the mapping of parameters and return type.
  460. // Since the function must take at least two arguments—self and _cmd, the second and third
  461. // characters must be “@:” (the first character is the return type).
  462. func (c Class) AddMethod(name SEL, imp IMP, types string) bool {
  463. return class_addMethod(c, name, imp, types)
  464. }
  465. // AddProtocol adds a protocol to a class.
  466. // Returns true if the protocol was added successfully, otherwise false (for example,
  467. // the class already conforms to that protocol).
  468. func (c Class) AddProtocol(protocol *Protocol) bool {
  469. return class_addProtocol(c, protocol)
  470. }
  471. // InstanceSize returns the size in bytes of instances of the class or 0 if cls is nil
  472. func (c Class) InstanceSize() uintptr {
  473. return class_getInstanceSize(c)
  474. }
  475. // InstanceVariable returns an Ivar data structure containing information about the instance variable specified by name.
  476. func (c Class) InstanceVariable(name string) Ivar {
  477. return class_getInstanceVariable(c, name)
  478. }
  479. // Ivar an opaque type that represents an instance variable.
  480. type Ivar uintptr
  481. // Offset returns the offset of an instance variable that can be used to assign and read the Ivar's value.
  482. //
  483. // For instance variables of type ID or other object types, call Ivar and SetIvar instead
  484. // of using this offset to access the instance variable data directly.
  485. func (i Ivar) Offset() uintptr {
  486. return ivar_getOffset(i)
  487. }
  488. func (i Ivar) Name() string {
  489. return ivar_getName(i)
  490. }
  491. // Protocol is a type that declares methods that can be implemented by any class.
  492. type Protocol [0]func()
  493. // GetProtocol returns the protocol for the given name or nil if there is no protocol by that name.
  494. func GetProtocol(name string) *Protocol {
  495. return objc_getProtocol(name)
  496. }
  497. // Equals return true if the two protocols are the same.
  498. func (p *Protocol) Equals(p2 *Protocol) bool {
  499. return protocol_isEqual(p, p2)
  500. }
  501. // IMP is a function pointer that can be called by Objective-C code.
  502. type IMP uintptr
  503. // NewIMP takes a Go function that takes (ID, SEL) as its first two arguments.
  504. // It returns an IMP function pointer that can be called by Objective-C code.
  505. // The function panics if an error occurs.
  506. // The function pointer is never deallocated.
  507. func NewIMP(fn interface{}) IMP {
  508. ty := reflect.TypeOf(fn)
  509. if ty.Kind() != reflect.Func {
  510. panic("objc: not a function")
  511. }
  512. // IMP is stricter than a normal callback
  513. // id (*IMP)(id, SEL, ...)
  514. switch {
  515. case ty.NumIn() < 2:
  516. fallthrough
  517. case ty.In(0) != reflect.TypeOf(ID(0)):
  518. fallthrough
  519. case ty.In(1) != reflect.TypeOf(SEL(0)):
  520. panic("objc: NewIMP must take a (id, SEL) as its first two arguments; got " + ty.String())
  521. }
  522. return IMP(purego.NewCallback(fn))
  523. }