The interoperability of swift with C or C++ goes over Objective-C, via the bridging header.
In this Objective-C header, you may include C headers, since Objective-C is interoperable with C. Swift can then not only work with the C functions, but also with C structures and unions.
You may also use interoperability with C++ using Objective-C++. Wowever, neither Objective-C nor Swift can work with C++ classes and their semantic. So you'll face the same issues than when trying to work with C++ from C. In this and this answers, you'll find more infos about C++ interoperability.
So what's easier to call from/to Swift? Definitively C
Small step by step demo:
1) Create a Swift project in XCode
2) Add a c file test.c
3) When you've added the c file, XCode will ask you if a briging header is to be created: just confirm.
4) Use the following code
In the bridging header (or in a header included in the bridging header):
// C functions
int myCFunction(int a);
void myCFunctionWithCallback(int a, int (*f)(int));
// Swift functions accessible from C
extern int mySwiftFunction(int x);
Example test.c
file:
#include <stdio.h>
// simple example with a hardcoded swift callback
int myCFunction(int a)
{
printf ("myCFunction in C called with %d\n", a);
printf ("Now calling Swift from C :\n");
int z = mySwiftFunction(10);
printf ("Result returned in C:%d\n", z);
return 2*a;
}
// example with a function pointer to a swift callback
void myCFunctionWithCallback(int a, int (*f)(int))
{
printf ("myCFunctionWithCallback in C called with %d\n", a);
printf ("Now calling Swift from C :\n");
int z = f(a);
printf ("Result returned in C:%d\n", z);
}
Example main.swift
file:
import Foundation
@_silgen_name("mySwiftFunction") // vital for the function being visible from C
func mySwiftFunction(x: Int) -> Int
{
print ("mySwiftFUnction called in Swift with \(x)")
return 3*x
}
func mySwiftCallback(x: Int32) -> Int32
{
print ("mySwiftCallback called in Swift with \(x)")
return 7*x
}
print("Starting Swift/C interoperability demo !")
let a = myCFunction(12);
print ("returned result in Swift is \(a)")
print ("Now test with a callback function pointer:")
myCFunctionWithCallback(13, mySwiftCallback )
The trick @_silgen_name
for making swift functions visible in C is explained in this other SO answer and is documented here