4

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:

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

LombaX
  • 17,265
  • 5
  • 52
  • 77

1 Answers1

2

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 :-)

LombaX
  • 17,265
  • 5
  • 52
  • 77