在Swift中使用CFNotificationCallback,或在Swift中使用@convention(c)块

我正在尝试使用(现在私有的)CTTelephonyCenteraddobserver C函数和CFNotificationCallback回调块来侦听CoreTelephony通知.

我的桥接头(外部私有C函数):

#include <CoreFoundation/CoreFoundation.h>

#if __cplusplus
extern "C" {
#endif

#pragma mark - API

    /* This API is a mimic of CFNotificationCenter. */

    CFNotificationCenterRef CTTelephonyCenterGetDefault();
    void CTTelephonyCenteraddobserver(CFNotificationCenterRef center,const void *observer,CFNotificationCallback callBack,CFStringRef name,const void *object,CFNotificationSuspensionBehavior suspensionBehavior);
    void CTTelephonyCenterRemoveObserver(CFNotificationCenterRef center,const void *object);
    void CTTelephonyCenterRemoveEveryObserver(CFNotificationCenterRef center,const void *observer);

    void CTIndicatorsGetSignalStrength(long int *raw,long int *graded,long int *bars);

#pragma mark - DeFinitions

    /* For use with the CoreTelephony notification system. */
    extern CFStringRef kCTIndicatoRSSignalStrengthNotification;

#if __cplusplus
}
#endif

我的Swift代码

let callback: CFNotificationCallback = { (center: CFNotificationCenter?,observer: UnsafeRawPointer?,name: CFString?,object: UnsafeRawPointer?,info: CFDictionary?) -> Void in
    // ...
}

CTTelephonyCenteraddobserver(CTTelephonyCenterGetDefault().takeUnretainedValue(),nil,callback,kCTIndicatoRSSignalStrengthNotification.takeUnretainedValue(),.coalesce)

但是,我无法获得我的完成变量的签名以匹配CFNotificationCallback typealias的要求.

06002

如何让@convention(c)闭包在Swift中很好地玩?

让编译器推断闭包的签名工作正常:
let callback: CFNotificationCallback = { center,observer,name,object,info in
    //works fine
}

试图在闭包声明中指定@convention(c)会出错:

let callback: CFNotificationCallback = { @convention(c) (center: CFNotificationCenter?,info: CFDictionary?) -> Void in
    //Attribute can only be applied to types,not declarations.
}

似乎正在发生的事情是,当您手动声明闭包的类型时,它会强制编译器使用该确切类型.但这在技术上是一个闭包声明而不是类型声明,因此不允许@convention属性.当允许编译器推断闭包的类型时(根据它所存储的变量的类型),它也可以推断出属性.

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...