2015-01-16 2 views
1

나는 IOKit에 대한 예를 발견신속하게 C-Style 콜백 함수를 구현하는 방법은 무엇입니까?

var notification:io_object_t 

let matching:NSDictionary = IOServiceNameMatching("IODisplayWrangler").takeRetainedValue() 
let displayWrangler = IOServiceGetMatchingService(kIOMasterPortDefault, matching) 
let notificationPort = IONotificationPortCreate(kIOMasterPortDefault) 
    IOServiceAddInterestNotification(notificationPort, displayWrangler, kIOGeneralInterest, displayPowerNotificationsCallback, nil, &notification) 

CFRunLoopAddSource (CFRunLoopGetCurrent(), IONotificationPortGetRunLoopSource(notificationPort), kCFRunLoopDefaultMode); 
    IOObjectRelease (displayWrangler); 

위의 예는 나에게 분명하다 - 지금까지. 그러나 IOServiceAddInteresNotification은 콜백 함수를 원합니다. .m -file에 C-Style 함수를 구현하여이 작업을 간단하게 수행 할 수 있습니다.

설명서에 IOServiceInterestCallback 유형의 콜백을 사용해야한다고 나와 있습니다.

은 다음과 같이 C-스타일에서 그것은 정의됩니다

typedef void (*IOServiceInterestCallback)(void *refcon, io_service_t service, uint32_t messageType, void *messageArgument); 

을 그리고 objC에 모든 것을 완벽하게 해결할 것으로 보인다. 신속한 동등한 솔루션은 무엇입니까? 어떻게이 C 또는 objC 파일을 만들지 않고 콜백 함수를 선언합니까?

아이디어가 있으십니까?

건배,

+0

objective-c에 설명되어 있으며 swift의 함수와 블록 (클로저) 유형은 일반적으로 서로 바꿔 사용할 수 있습니다. 필요한 서명과 일치하고 사용하는 신속한 함수를 작성해 보았습니까? –

+0

예, 이미이 아이디어를 시도했습니다. 그러나 신속하게 구현할 수 없었던 이유는 void *와 uint32_t (존재하지 않음)에 대해 불평했습니다. – JackPearse

+0

IOServiceInterestCallback은 swift에서 정의됩니다. "func IOServiceInterestCallback displayPowerNotificationsCallback {(...)} – JackPearse

답변

2

폐쇄는 CFunctionPointer와 호환되지 않습니다과 같이 스위프트의 콜백과 같은 C 함수를 만들 수 없습니다. Objective-C 또는 C에서 몇 가지 해결 방법을 구현할 수 있습니다. 예제는 Objective-C Wrapper for CFunctionPointer to a Swift Closure

+0

같은 것을 사용하여 미리 정의 된 함수 프로토 타입을 사용하여 콜백을 구현하는 방법을 알고 있습니까? 즉, 콜백을 위해서만 objC 래퍼를 사용해야한다는 의미입니다. 그러나 closure가 CFunctionPointer와 호환되지 않는다는 것을 알면 좋습니다. – JackPearse

관련 문제