Is it possible to do calls to swift functions out of regular c functions

321 views Asked by At

I searched the net, and I found a lot of information about calling regular C functions in some swift code. But I haven't found any information about the inverse way. Calling a swift function in regular C.

With Objective-C, I just created a C compatible header file, and used an objective-C body to do the work.

Does anybody know how I have to do it,to call a swift function instead.

PS. The main source code used, is written in plain C, not C++ or objective-C. Because it also needs to run on a custom device. The purpose that I want to interact with swift is to create a simulator for the device.

Peter.

1

There are 1 answers

0
hnh On

In Swift 2 you can pass in C function pointers to your Swift functions or non-capturing closures.

Example C:

static void (*myCallback)(void);
void setCallback(void (*cb)(void)) {
  myCallback = cb;
}

main() {
  if (myCallback) myCallback();
}

Example Swift 2:

setCallback { print("do it") }

SwiftyExpat is a demo of this.