I want to call the callback function from native code:
From header:
void load_all(Client *client,
void (*cb_result)(const ResponseWrapper*),
void (*cb_error)(char*));
This is my callback in Swift:
let result: @convention(c) (UnsafePointer<ResponseWrapper>?) -> Void = { pointer in
if let ResponseWrapper = pointer?.pointee {
print("data \(data.length)")
}
}
When I try to return results from result
callback to swift I got next error:
A C function pointer cannot be formed from a closure that captures context
What is the best way to overcome this limitation?
Is the only way to save an instance of my class to a pointer, send to native code and cast back to object?
let owner = UnsafeMutableRawPointer(Unmanaged.passRetained(callbackWrapper).toOpaque())
let owner: Response = Unmanaged.fromOpaque($0!).takeUnretainedValue()
This is not working as well:
func loadAll() {
//Loader class
let ownedPointer = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())
let result: @convention(c) (UnsafePointer<ResponseWrapper>?) -> Void = { pointer in
if let ResponseWrapper = pointer?.pointee {
print("data \(data.length)")
}
let newSelf:Loader = Unmanaged.fromOpaque(ownedPointer).takeUnretainedValue()
}
}
My current solution:
- Swift : gist.github.com/xajik/fe360b705f63ceba4a71f94d1ce2dc41
- Rust: gist.github.com/xajik/8b532c44e3a267a5d8ae450ea11ad41c