I have Swift based project that uses a (third party) C-based library
I can use all the code from the library without any problems
Only the event handling I can't get to work:
The library defines a type for any callback functions:
typedef void (*callBackFunctionType)(SubEventType subEventType,
UInt32 param2,
UInt32 param3);
And a function to register an event listener and the callback to be used with it:
SHARED_FUNCTION void addEventListener(void * eventCallback, TYPOFEvent eventType);
On the Swift side I try to implement this as follows:
// Global scope
public typealias swiftCallbackFunctionType = @convention(c) (SubEventType , UInt32, UInt32) -> Void
func callBackFunction(subEvent: SubEventType, param2: UInt32, param3: UInt32){
print("Callback function gets called")
}
var callBackFuctionPointer:swiftCallbackFunctionType = callBackFunction
// Class scope
class func registerForEvents(){
addEventListener(&callBackFuctionPointer, DEVICE_POWER_UP)
}
however my app crashes when an DEVICE_POWER_UP-event gets fired
Unrecommended Swift-only solution :
class func registerForEvents(){
let callBackFunction: callBackFunctionType = {subEventType, param1, param2 in
print("Callback function gets called")
}
addEventListener(unsafeBitCast(callBackFunction, to: UnsafeMutableRawPointer.self) , DEVICE_POWER_UP)
}
(Assuming the `callBackFunctionType` is imported into Swift.)
But the C-wrapper would not be so difficult...
EventListenerWrapper.h:
#ifndef EventListenerWrapper_h
#define EventListenerWrapper_h
#include <stdio.h>
#include "EventListener.h"
SHARED_FUNCTION void addEventListenerWrapped(callBackFunctionType eventCallback, TYPOFEvent eventType);
#endif /* EventListenerWrapper_h */
EventListenerWrapper.c:
#include "EventListenerWrapper.h"
void addEventListenerWrapped(callBackFunctionType eventCallback, TYPOFEvent eventType) {
addEventListener(eventCallback, eventType);
}
(You may need to modify some parts according to the actual headers of the library.)
From Swift:
class func registerWrappedForEvents(){
let callBackFunction: callBackFunctionType = {subEventType, param1, param2 in
print("Callback function gets called")
}
addEventListenerWrapped(callBackFunction, DEVICE_POWER_UP)
}
You can avoid using horrible `unsafeBitCast`.