3

I'm trying to convert some Objective-C to Swift code.

How can I convert this as I couldn't find any equivalent in swift.

((void (*)(id, SEL, id, id))objc_msgSend)(anObject, mySelector, anotherObject, lastObject)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
anasaitali
  • 1,504
  • 21
  • 30

2 Answers2

6

Swift 3.1

let handle : UnsafeMutableRawPointer! = dlopen("/usr/lib/libobjc.A.dylib", RTLD_NOW)
unsafeBitCast(dlsym(handle, "objc_msgSend"), to:(@convention(c)(Any?,Selector!,Any?,Any?)->Void).self)(anObject,#selector(mySelector),anotherObject,lastObject)
dlclose(handle)

You could alternatively use class_getMethodImplementation

unsafeBitCast(class_getMethodImplementation(type(of: anObject), #selector(mySelector)), to:(@convention(c)(Any?,Selector!,Any?,Any?)->Void).self)(anObject,#selector(mySelector), anotherObject,lastObject)
Kamil.S
  • 5,205
  • 2
  • 22
  • 51
2

The Objective-C Runtime Reference has all the runtime functions listed.

Some of the functions have a Swift representation, some don't. For example, class_getName is available in Swift, but sel_getName is not.

The function objc_msgSend is not available to Swift.


After a quick search, I found this: Call a method from a String in Swift. Create an Objective C wrapper for objc_msgSend that will do the work for you. Not a great answer, but it seems to be the working solution for now.

Community
  • 1
  • 1
Jeffery Thomas
  • 42,202
  • 8
  • 92
  • 117