Swift C Callback

,

Could i see an example in which Swift sets a c function to callback its own function, SwiftAddTwoNumbers?. if C function call_AddTwoNumbers is executed anywhere in the .c file, it will calls back the SwiftAddTwoNumbers.

swift file like viewcontroller:

func SwiftAddTwoNumbers(a: Int, b: Int) {
  var sum = a + b
  print("Sum:", sum)
}

.c file:
void call_AddTwoNumbers(int i, int j
{
}

This thread may help: Best way to call a Swift function from C?. Nearly a year since the last update so you may be lucky in Swift 5.7.

i am using swift 4.

I do not know if it helps, but in this experimental Swift binding of the Xerces XML parser I needed to realize a callback from C++ and even with the following special case (that you may not need):

I needed to pass a Swift object to C++ and then being able to use it in the callback in Swift again (the object being passed around being a Swift consumer of the parse events). The trick was that when you have a raw pointer in Swift, you can tell Swift that this raw pointer points to an instance of a certain type, so:

Making a raw pointer to pass it to C++:


xercesWrapper.parseConsumer = UnsafeMutableRawPointer(Unmanaged.passUnretained(parseConsumer).toOpaque())

Making it a Swift object again when getting it back in the callback:

let consumer = Unmanaged<XMLParseConsumer>.fromOpaque(consumerRef).takeUnretainedValue()

…but maybe there is a better way to do this (I am not sure how reference counting is affected). The C++ binding for Swift got much better in the meantime, I think.

At least you have an example of a callback (in C++).

I would recommend to use a more current version of Swift.

1 Like