Does Swift not work with function pointers?
Apple has made function pointers available as of beta 3, however they can only be referenced not called.
Using Swift with Cocoa and Objective-C
Function Pointers
C function pointers are imported into Swift as
CFunctionPointer<Type>
, whereType
is a Swift function type. For example, a function pointer that has the typeint (*)(void)
in C is imported into Swift asCFunctionPointer<() -> Int32>
Beta 3 Release Notes (PDF)
Function pointers are also imported now, and can be referenced and passed around. However, you cannot call a C function pointer or convert a closure to C function pointer type.
This answer refers to an earlier version of the Swift language and may no longer be reliable.
While C function pointers are not available in Swift, you can still use swift closures which are passed to C functions as blocks.
Doing so requires a few "shim" routines in C to take the block and wrap it in a C function. The following demonstrates how it works.
Swift:
func foo(myInt: CInt) -> CInt {
return myInt
}
var closure: (CInt) -> CInt = foo;
my_c_function(closure)
C:
void my_c_function(int (^closure)(int))
{
int x = closure(10);
printf("x is %d\n", x);
}
Of course what you choose to do with the closure, and how you store and recall it for use is up to you. But this should give you a start.
In the Apple documentation it is noted that C function pointers are not imported in Swift
.