I am working on xcode8 swift 3.0 project. It needs to access a C++ library which will need a callback function to send data back to swift caller asynchronizely. The callback does work if it is called right inside the RegisterCallBack function. However, if it crashes if call it outside the RegisterCallBack function.
in my swift file ViewController.swift
override func viewDidLoad() {
super.viewDidLoad()
var closure: () -> Void = testfunc;
RegisterCallBack(closure)
run_swiftfunc()
}
func testfunc(){
print("test func in view contriller ");
}
....
// in my wrapper.h file
...
void run_swiftfunc();
void RegisterCallBack(void (^closure)());
...
// in my wrapper.cpp file
extern "C" {
typedef void (^callbackfunc)();
callbackfunc swiftFunc;
void RegisterCallBack(void (^closure)()){
swiftFunc = closure;
printf("function pointer 0x%x \n", (void*) swiftFunc);
swiftFunc(); //works well
}
void run_swiftfunc(){
printf("function pointer 0x%x \n", (void*) swiftFunc);
swiftFunc(); // fail, EXC_BAD_ACCESS
}
...
}
//log print: RegisterCallBack function pointer 0x1300cd30
run_swiftfunc
function pointer 0x1300cd30
test func in view contriller
run_swiftfunc
function pointer 0x1300cd30
(lldb) ---->EXC_BAD_ACCESS(code =..
The swiftfunc address is same both are 0x1300cd30. How to preserve the swiftfunc block?