2016-10-19 28 views
1

私は、(現在プライベートの) C関数とCFNotificationCallbackコールバックブロックを使用して、CoreTelephony通知を待ち受けようとしています。SwiftのCFNotificationCallback、またはSwiftの@convention(c)ブロックを使用

マイブリッジのヘッダー(プライベートC関数をexternに):

#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 *observer, CFStringRef name, 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 

マイスウィフトコード:

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

CTTelephonyCenterAddObserver(CTTelephonyCenterGetDefault().takeUnretainedValue(), nil, callback, kCTIndicatorsSignalStrengthNotification.takeUnretainedValue(), nil, .coalesce) 

しかし、私は私のcompletion変数の署名が一致して取得することはできませんタイプ番号のCFNotificationCallbackの要件

Cannot convert value of type 
'(CFNotificationCenter?, UnsafeRawPointer?, CFString?, UnsafeRawPointer?, CFDictionary?) -> Void' 
to specified type 
'CFNotificationCallback' (aka '@convention(c) (Optional<CFNotificationCenter>, Optional<UnsafeMutableRawPointer>, Optional<CFNotificationName>, Optional<UnsafeRawPointer>, Optional<CFDictionary>) ->()') 

どのように私は、スウィフトにうまくプレーする@convention(c)閉鎖を得ることができますか?コンパイラはクロージャの署名が正常に動作推測まかせ

+1

'observer'が' UnsafeMutableRawPointer'で、 'UnsafeRawPointer'ではないので、コンパイルされません。 –

答えて

1

:クロージャの宣言で@convention(c)を指定しようとすると

let callback: CFNotificationCallback = { center, observer, name, object, info in 
    //works fine 
} 

がエラーを与える:何が起こっているのはそのときであるように

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

に思えますクロージャの型を手動で宣言すると、コンパイラはその正確な型を強制的に使用します。しかし、これは技術的にクロージャ宣言であり型宣言ではないため、@convention属性は使用できません。コンパイラがクロージャの型を(格納されている変数の型から)推測することができるとき、コンパイラはその属性も推測できます。

+0

ああそうなのですが、私は事を過度に複雑化していました。ありがとう! – JAL

関連する問題