Reputation: 11494
I am currently working on a library in Swift that has a version already written in C. As the version in C already has a large testing suite, I would like to just run the Swift code through the C tests.
Is it possible to call Swift in C?
Upvotes: 1
Views: 84
Reputation: 4891
To call Swift from C one can wrap Swift code in Objective-C functions callable from C. A trivial contrived example follows.
Swift code:
import Foundation
@objc public class ClassSwift : NSObject {
public func addIntegers(int1:Int32, int2:Int32) -> Int32 {
return int1 + int2;
}
}
Objective-C wrapper:
// Mixed 1a is the name of my sample target
// You can see the name of your Swift header in
// Objective-C Generated Interface Header Name under Build Settings.
#import "Mixed_1a-Swift.h"
// This function is callable from C, even though it calls Swift code!
int addIntsC(int i1, int i2)
{
ClassSwift * cs = [[ClassSwift alloc] init];
return [cs addIntegersWithInt1:i1 int2:i2];
}
And, finally, here's the C code:
#include <stdio.h>
int addIntsC(int, int);
int main(int argc, const char * argv[]) {
int result = addIntsC(3, 7);
if (result == 10) puts("Test passed!");
else puts("Failed... :(");
return 0;
}
Upvotes: 1