Representing NULL Function Pointers to C Functions in Swift

后端 未结 1 1073
你的背包
你的背包 2021-01-17 20:21

Consider the private-yet-sort-of-documented Cocoa C functions _NSLogCStringFunction() and _NSSetLogCStringFunction(). _NSLogCStringFunction(

1条回答
  •  北海茫月
    2021-01-17 20:32

    The Swift mapping of the (Objective-)C declaration

    extern void _NSSetLogCStringFunction(void(*)(const char*, unsigned, BOOL));
    

    is

    public func _NSSetLogCStringFunction(_: (@convention(c) (UnsafePointer, UInt32, ObjCBool) -> Void)!)
    

    The easiest solution would be to put the Objective-C extern declaration into an Objective-C header file and include that from the bridging header.

    Alternatively, in pure Swift it should be

    typealias NSLogCStringFunc = @convention(c) (UnsafePointer, UInt32, ObjCBool) -> Void
    
    @_silgen_name("_NSSetLogCStringFunction")
    func _NSSetLogCStringFunction(_: NSLogCStringFunc!) -> Void
    

    In either case, the function parameter is an implicitly unwrapped optional, and you can call it with nil. Example:

    func myLogger(message: UnsafePointer, _ length: UInt32, _ withSysLogBanner: ObjCBool) -> Void {
        print(String(format:"myLogger: %s", message))
    }
    
    _NSSetLogCStringFunction(myLogger) // Set NSLog hook.
    NSLog("foo")
    _NSSetLogCStringFunction(nil) // Reset to default.
    NSLog("bar")
    

    Output:

    myLogger: foo
    2016-04-28 18:24:05.492 prog[29953:444704] bar
    

    0 讨论(0)
提交回复
热议问题