加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

比较Swift中C函数的指针

发布时间:2020-12-14 05:29:45 所属栏目:百科 来源:网络整理
导读:我正在寻找一种方法来比较指向c函数的指针.例如.: let firstHandler = NSGetUncaughtExceptionHandler()NSSetUncaughtExceptionHandler(onUncaughtException)let secondHandler = NSGetUncaughtExceptionHandler()if firstHandler == secondHandler { debug
我正在寻找一种方法来比较指向c函数的指针.例如.:
let firstHandler = NSGetUncaughtExceptionHandler()

NSSetUncaughtExceptionHandler(onUncaughtException)
let secondHandler = NSGetUncaughtExceptionHandler()

if firstHandler == secondHandler {
    debugPrint("equal")
}

更新==,也不是===有效

在目标C中,我可以表达如下:

NSUncaughtExceptionHandler *firstHandler = NSGetUncaughtExceptionHandler();

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

if (firstHandler == secondHandler) {
    NSLog(@"equal");
}

提前致谢

通常,您无法在Swift中比较函数的相等性.
但是,NSSetUncaughtExceptionHandler返回一个
(@convention(c) (NSException) -> Swift.Void)?

即(可选的)C兼容功能,并且这样的功能可以是
强制转换为(可选)原始指针
unsafeBitCast:

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

然后可以比较平等

if ptr1 == ptr2 {.. }

一个独立的例子:

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) 

print(ptr1 == ptr2) // false

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读