2

Is it possible to pass a closure from a Swift program into an API where the corresponding argument has been marked as CFunctionPointer?

I've come across indications (e.g. here) that this was not possible with (by now obsolete) beta versions of Xcode 6.

However, you cannot call a C function pointer or convert a closure to C function pointer type.

Is it possible by now and if so how?

For instance, how could one define a closure in Swift that would be accepted as AudioServicesSystemSoundCompletionProc in a call to AudioServicesAddSystemSoundCompletion?

This answer employs both Swift and Objective-C to arrive at a solution. Is one possible with a Swift class alone?

Community
  • 1
  • 1
Drux
  • 11,992
  • 13
  • 66
  • 116
  • possible duplicate of [Objective-C Wrapper for CFunctionPointer to a Swift Closure](http://stackoverflow.com/questions/26138658/objective-c-wrapper-for-cfunctionpointer-to-a-swift-closure) – David Berry Jan 26 '15 at 17:54

1 Answers1

4

No, not yet possible with Swift alone.

However, you cannot call a C function pointer or convert a closure to C function pointer type.

Is still in effect and up to date. There is no way to define or convert closure to C function in Swift. You can only refer to already defined C functions.

Kirsteins
  • 27,065
  • 8
  • 76
  • 78
  • Can you please quote from a current piece of Apple documentation to back this up. (Then I'll accept the answer.) – Drux Jan 26 '15 at 10:25
  • Basically, `However, you cannot call a C function pointer or convert a closure to C function pointer type.` is still in effect. – Kirsteins Jan 26 '15 at 10:28