Representing NULL Function Pointers to C Functions in Swift

早过忘川 提交于 2019-12-01 16:01:23

The Swift mapping of the (Objective-)C declaration

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

is

public func _NSSetLogCStringFunction(_: (@convention(c) (UnsafePointer<Int8>, 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<Int8>, 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<Int8>, _ 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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!