Best way to call a Swift function from C?

There's no official way yet. Aside from name mangling, Swift functions use a different calling convention from C. Unofficially, if you're willing to deal with more than the usual amount of code breakage and compiler bugs, there's an unofficial attribute @_cdecl that does this:

@_cdecl("mymodule_foo")
func foo(x: Int) -> Int {
  return x * 2
}

which you can then call from C:

#include <stdint.h>

intptr_t mymodule_foo(intptr_t);

intptr_t invoke_foo(intptr_t x) {
  return mymodule_foo(x);
}
6 Likes