4

I have C API that I use from Swift.

In Swift, I have:

enum GetSnapshotResult {
    case success(snapshot: UIImage, String)
    case failure()
}

func getSnapshot(completion: @escaping (GetSnapshotResult) -> Void) {
    CAPIGetSnapshot(nil) { (_) in 
        completion(
            .success(
                snapshot: UIImage(),
                "test"
            )
        )
    }
}

And in C API:

void CAPIGetSnapshot(void * ptr, void(*callbackOnFinish)(void *)) {
    //do something in background thread
    //and on its finish, call callbackOnFinish from thread 
    
    callbackOnFinish(ptr);
}

However, with this I get:

A C function pointer cannot be formed from a closure that captures context

How do I solve this?

2
  • See stackoverflow.com/q/33260808/1187415
    – Martin R
    Jan 23, 2021 at 16:00
  • @MartinR I have tried it, but I cannot use let observer = UnsafeRawPointer(Unmanaged.passUnretained(completion).toOpaque()). It errors with GetSnapshotResult not being class. I can create class wrapper and assign closure to variable, however, I am not sure what happens with @escaping Jan 23, 2021 at 16:03

1 Answer 1

6

You need a wrapper class so that a void pointer to the instance can be tunneled through the C function to the callback. The combination of passRetained() and takeRetainedValue() ensures that the wrapper instance is released only after the completion function has been called.

func getSnapshot(completion: @escaping (GetSnapshotResult) -> Void) {
    
    class Wrapper {
        let completion: (GetSnapshotResult) -> Void
        init(completion: @escaping (GetSnapshotResult) -> Void) {
            self.completion = completion
        }
    }

    let wrapper = Wrapper(completion: completion)
    let observer = UnsafeMutableRawPointer(Unmanaged.passRetained(wrapper).toOpaque())

    CAPIGetSnapshot(observer) { theObserver in
        let theWrapper = Unmanaged<Wrapper>.fromOpaque(theObserver!).takeRetainedValue()
        theWrapper.completion(
            .success( snapshot: UIImage(), "test")
        )
    }
}

Some remarks:

  • I am assuming that the C function passes the ptr argument to the callback.

  • passRetained(wrapper) retains the object. That ensures that the wrapper instance is not released when the getSnapshot() function returns.

  • takeRetainedValue() in the closure consumes the retain. As a consequence, the wrapper instance is released when the closure returns.

  • completion is a closure and closures are reference types. wrapper.completion holds a reference to that closure as long as the wrapper instance exists.

  • Of course you can use the same variable names (“observer”, “wrapper”) inside the closure. I chose different names here (“theObserver”, “theWrapper”) only to emphasize that they are different variables, i.e. that the closure does not capture context anymore.

  • observer needs to be a mutable raw pointer only because the first argument of the C function is declared as void * ptr. If you can change the function declaration to

    void CAPIGetSnapshot(const void * ptr, void(*callbackOnFinish)(const void *))
    

    then let observer = UnsafeRawPointer(...) works as well.

  • For more information about conversion between object references to void pointers see for example How to cast self to UnsafeMutablePointer<Void> type in swift.

Instead of a custom wrapper class you can also take advantage of the fact that arbitrary Swift values are automatically boxed in a class type when cast to AnyObject (see for example AnyObject not working in Xcode8 beta6?).

func getSnapshot(completion: @escaping (GetSnapshotResult) -> Void) {
    
    let wrapper = completion as AnyObject
    let observer = UnsafeRawPointer(Unmanaged.passRetained(wrapper).toOpaque())
    
    CAPIGetSnapshot(observer) { theObserver in
        let theCompletion = Unmanaged<AnyObject>.fromOpaque(theObserver!).takeRetainedValue()
            as! ((GetSnapshotResult) -> Void)
        theCompletion(
            .success( snapshot: UIImage(), "test")
        )
    }
}

The forced unwraps and forced casts are safe here because you know what it passed to the function. A failure to unwrap or cast would indicate a programming error. But I would prefer the first version instead of relying on this “magic”.

3
  • Hi. In my case C calls the callback from a different thread. As a result EXC_BAD_ACCESS (code=EXC_I386_GPFLT) happens on the theWrapper.completion() call. Before I open one more question on SO - maybe there is a simple way to call swift callbacks from an async C library?
    – Alexander
    Feb 21, 2022 at 23:24
  • 1
    @Alexander: Generally, that solution should work even if the callback is called on a different thread. I think that more information is needed to solve your problem. You might want to ask a new question (ideally with a self-contained example demonstration the problem). – If you ping me here then I'll have a look at it :)
    – Martin R
    Feb 24, 2022 at 8:35
  • 1
    Sorry for longer response. You answered on the 24th of February and my life was quiet busy after that date :/ I ended up executing code from the callback on the main thread (as far as I understand it), so it works: DispatchQueue.main.async { ... }
    – Alexander
    Sep 8, 2022 at 6:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.