Function callback from C to Swift

I have this C function that simply calls back another function passed as a parameter

void call_my_function(void (*callback_function)())
{
    callback_function();
}

This is C test code:

  • “Stream is sending an event before being opened”
  • Restore view state without animating segue
  • UIDevice currentDevice model possible values
  • Accessing variables from another ViewController in Swift
  • GoogleMaps (GMSView) Won't display in iOS
  • How to save an array to .plist in the App's mainBundle in swift
  • void func_to_call()    // a simple test function passed in as a callback
    {
        printf("function correctly called");
    }
    
    void test()   // entry point
    {
        void (*foo)();
        foo = &func_to_call;
        call_my_function(foo);     // pass the address of "func_to_call()" to "call_my_function()"
    }
    

    Essentially, from test(), I call call_my_function() passing in the address of func_to_call(), and then call_my_function() calls back func_to_call().

    From swift I see correctly the functions test() and func_to_call(), but it seems that

    void call_my_function(void (*callback_function)())
    

    is not recognized (use of unresolved identifier)
    If I remove the parameter void (*callback_function)() then the function is recognized again.

    What can I do to pass a Swift function address to C and have it called back? Is it possible?
    Thanks

    Solutions Collect From Internet About “Function callback from C to Swift”

    Apple confirmed me, on the dev forum, that it is not supported now, and requested me to fill a new request on the bugreporter.

    Moreover, I give to the readers another detail:

    It seems that in the compiled binary the symbols for all swift functions are already available and bridged to be accessible from C (even in a swift-only app)

    I made an app called FunctionTest, iPhone App with this function in a swift file

    func thisIsATestFunction()
    {
    println(“test”)
    }

    compiled, and then from Terminal:

    nc /Users/xxx/Library/Developer/Xcode/DerivedData/FunctionTest-hhrbtzsuyrdoftfnbakosvenaiak/Build/Products/Debug-iphonesimulator/FunctionTest.app/FunctionTest

         U _NSStringFromClass
         U _OBJC_CLASS_$_NSString
         U _OBJC_CLASS_$_UIResponder
         U _OBJC_CLASS_$_UIViewController
         U _OBJC_CLASS_$_UIWindow
    000088c8 S _OBJC_CLASS_$__TtC12FunctionTest11AppDelegate
    00008888 S _OBJC_CLASS_$__TtC12FunctionTest14ViewController
    .........
    .........
    00003840 T __TF12FunctionTest19thisIsATestFunctionFT_T_          <--- this is my test function
    

    Calling from c the address 00003840 executed the function

    void (* func)() = 0x00003840;
    func();    // the swift function is executed
    

    So I think that this is already work-in-progress…hoping that they will implement this functionality in the next releases 🙂