考虑使用私有但有点记录的Cocoa C函数
在C语言中,我可以将一个空的函数指针传递给
我如何在Swift中表示指向
_NSLogCStringFunction()
和 _NSSetLogCStringFunction()
。 _NSLogCStringFunction()
返回一个函数指针,指向Objective-C运行时在幕后使用的C函数,用于NSLog()
,而_NSSetLogCStringFunction()
允许开发人员指定自己的C函数进行日志记录。 有关这两个函数的更多信息可以在此Stack Overflow问题和此WebObjects支持文章中找到。在C语言中,我可以将一个空的函数指针传递给
_NSSetLogCStringFunction()
:extern void _NSSetLogCStringFunction(void(*)(const char*, unsigned, BOOL));
_NSSetLogCStringFunction(NULL); // valid
然而,当我尝试在纯Swift中完成此操作时,遇到了一些问题:
/// Represents the C function signature used under-the-hood by NSLog
typealias NSLogCStringFunc = (UnsafePointer<Int8>, UInt32, Bool) -> Void
/// Sets the C function used by NSLog
@_silgen_name("_NSSetLogCStringFunction")
func _NSSetLogCStringFunction(_: NSLogCStringFunc) -> Void
_NSSetLogCStringFunction(nil) // Error: nil is not compatible with expected argument type 'NSLogCStringFunc' (aka '(UnsafePointer<Int8>, UInt32, Bool) -> ()')
如果我尝试使用unsafeBitCast
来规避这个编译时警告,我的程序会崩溃,并显示EXC_BAD_INSTRUCTION
(正如预期的那样,因为签名不正确):
let nullPtr: UnsafePointer<Void> = nil
let nullFuncPtr = unsafeBitCast(nullPtr, NSLogCStringFunc.self)
_NSSetLogCStringFunction(nullFuncPtr) // crash
我如何在Swift中表示指向
(void*)
, (void(*)(const char*, unsigned, BOOL))
或者 (UnsafePointer<Int8>, UInt32, Bool) -> Void
的NULL
函数指针?