Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New @convention(c) in Swift 2: How can I use it?

Tags:

swift

swift2

After migrating to Swift 2, I am getting this issue with an error stating that I should now use @convention(c) (T) -> U. I've tried permutations but so far no luck.

func foo(context: AnyObject?, width: CGFloat) -> Int {

}

let bar = unsafeBitCast(foo, CFunctionPointer<(UnsafeMutablePointer<Void>, Float) -> Int>.self)
like image 687
John Difool Avatar asked Jun 09 '15 18:06

John Difool


2 Answers

Passing a Swift closure to a C function taking a function pointer parameter is now supported in Swift 2, and, as you noticed, function types are specified with the @convention(c) attribute.

If you pass a closure directly as an argument to the C function then this attribute is inferred automatically.

As a simple example, if you have this C function

CGFloat myCFunction(CGFloat (callback)(CGFloat x, CGFloat y)) {
    return callback(1.1, 2.2);
}

then you can call it from Swift as

let result = myCFunction( {
    (x, y) -> CGFloat in
    return x + y
} )
print(result) // 3.3

which does exactly the same as the more verbose

let swiftCallback : @convention(c) (CGFloat, CGFloat) -> CGFloat = {
    (x, y) -> CGFloat in
    return x + y
} 

let result = myCFunction( swiftCallback )
print(result) // 3.3
like image 78
Martin R Avatar answered Oct 15 '22 17:10

Martin R


You no longer need to create a CFunctionPointer in Swift 2. Instead, you can annotate your type by calling convention, in this case c, and use it directly.

typealias CFunction = @convention(c) (UnsafeMutablePointer<Void>, Float) -> Int
let bar = unsafeBitCast(foo, CFunction.self)

The relevant bits of the @convention description in the Type Attributes section of The Swift Programming Language are:

The c argument is used to indicate a C function reference. The function value carries no context and uses the C calling convention.

like image 43
Mick MacCallum Avatar answered Oct 15 '22 19:10

Mick MacCallum