2

There is plenty of documentation available on how to use C/C++/Objective-C code in Swift. There is also information about using Swift in Objective-C.

However, I would like to know: Is it possible to use a Swift library in C or C++ code?

Jan Rüegg
  • 9,587
  • 8
  • 63
  • 105

2 Answers2

3

Short answer: yes, it is possible by wrapping Swift code in Objective-C code written in such a way that it is callable from C, as already suggested by @Josh Homann.

However, here are some things to note:

Having said that, here is a small oversimplified example, just for illustration purposes. Let's say we have this valuable functionality, available in Swift only, that we want to make use of in C:

@objc public class SwiftClass : NSObject {
    var myInt : Int32 = 111
    @objc public func processInteger(_ anInt : Int32) -> Int32 {
        myInt += anInt
        print("About to return \(myInt) from Swift")
        return myInt
    }
}

Objective-C wrapper, in a .m file, might look like this:

int32_t processIntegerOC(int32_t i) {
    puts("Entered Objective-C wrapper, about to use Swift...");
    SwiftClass * sc = [[SwiftClass alloc] init];
    return [sc processInteger:i];
}

Please note that this function can be called from C, but because it is in an Objective-C file it can use Swift. The function is called from C code as any other C function would be:

void processIntegerC(int32_t i) {
    puts("Entered processIntegerC(), about to call Objective-C wrapper...");
    int32_t retVal = processIntegerOC(i);
    printf("processIntegerC() has integer %d\n", retVal);   
}
Anatoli P
  • 4,791
  • 1
  • 18
  • 22
2

You can use swift from Objective C and Objective C is a strict superset of C. So if you wrap your swift function in Objective C then you can call it from C. See this thread on calling ObjC from C.

Josh Homann
  • 15,933
  • 3
  • 30
  • 33