比较Swift中C函数的指针

Tim*_*Tim 8 c pointers swift swift3

我正在寻找一种方法来比较指向c函数的指针.例如:

let firstHandler = NSGetUncaughtExceptionHandler()

NSSetUncaughtExceptionHandler(onUncaughtException)
let secondHandler = NSGetUncaughtExceptionHandler()

if firstHandler == secondHandler {
    debugPrint("equal")
}
Run Code Online (Sandbox Code Playgroud)

更新==,也没有===作品

目标CI可以表达如下:

NSUncaughtExceptionHandler *firstHandler = NSGetUncaughtExceptionHandler();

NSSetUncaughtExceptionHandler(onUncaughtException);
NSUncaughtExceptionHandler *secondHandler = NSGetUncaughtExceptionHandler();

if (firstHandler == secondHandler) {
    NSLog(@"equal");
}
Run Code Online (Sandbox Code Playgroud)

提前致谢

Mar*_*n R 6

通常,您无法在Swift中比较函数的相等性.但是,NSSetUncaughtExceptionHandler返回一个

(@convention(c) (NSException) -> Swift.Void)?
Run Code Online (Sandbox Code Playgroud)

即一个(可选的)C兼容函数,这样的函数可以强制转换为(可选)原始指针,具有 unsafeBitCast:

let ptr1 = unsafeBitCast(firstHandler, to: Optional<UnsafeRawPointer>.self) 
let ptr2 = unsafeBitCast(secondHandler, to: Optional<UnsafeRawPointer>.self) 
Run Code Online (Sandbox Code Playgroud)

然后可以比较平等

if ptr1 == ptr2 { .. }
Run Code Online (Sandbox Code Playgroud)

一个自包含的例子:

func exceptionHandler1(exception : NSException) { }

func exceptionHandler2(exception : NSException) { }

NSSetUncaughtExceptionHandler(exceptionHandler1)
let firstHandler = NSGetUncaughtExceptionHandler()
NSSetUncaughtExceptionHandler(exceptionHandler2)
let secondHandler = NSGetUncaughtExceptionHandler()

let ptr1 = unsafeBitCast(firstHandler, to: Optional<UnsafeRawPointer>.self) 
let ptr2 = unsafeBitCast(secondHandler, to: Optional<UnsafeRawPointer>.self) 

print(ptr1 == ptr2) // false
Run Code Online (Sandbox Code Playgroud)

  • @nayem:除非我弄错了,你可以重载==仅用于具体的函数签名,例如`func ==(lhs:(@ convention(c)(NSException) - > Void)?, rhs:(@ convention(c )(NSException) - > Void)?) - > Bool`,这可能不是很有用. (2认同)