John Gorter
John Gorter

Reputation: 2414

Call swift from c

I saw someone use swift code from android, using @_cdecl swift functions. I am able to compile to native using swiftc -emit-object, but when trying to link, I cant get the linker to work correctly..

I am trying to use g++ or clang(++) to compile and link a native swift object, has someone successfully done this already?

The errors I get are listed below:

Undefined symbols for architecture x86_64: 

"__T0S2SBp21_builtinStringLiteral_Bw17utf8CodeUnitCountBi1_7isASCIItcfC", referenced from:
      __T04main4testyyF in main.o
"__T0SSN", referenced from:
      __T04main4testyyF in main.o
"__T0s27_allocateUninitializedArraySayxG_BptBwlFyp_Tgq5", referenced from:
      __T04main4testyyF in main.o
"__T0s5printySayypGd_SS9separatorSS10terminatortF", referenced from:
      __T04main4testyyF in main.o
"__T0s5printySayypGd_SS9separatorSS10terminatortFfA0_", referenced from:
      __T04main4testyyF in main.o
"__T0s5printySayypGd_SS9separatorSS10terminatortFfA1_", referenced from:
      __T04main4testyyF in main.o
"_swift_bridgeObjectRelease", referenced from:
      __T04main4testyyF in main.o
"_swift_bridgeObjectRetain", referenced from:
      __T04main4testyyF in main.o

So basically I have two questions, can it be done and how? John.

Upvotes: 0

Views: 1604

Answers (1)

John Gorter
John Gorter

Reputation: 2414

So thanx to amine.ahd's pointer, I had the iphoneos toolchain location linked instead of the mac osx's.

The following command actually compiled and let me run a c program that calls a swift native library, even with parameters (char* on the c side, UnsafePointer on the swift side).

clang -o m m.o -lshared -L/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx  -L.

*-lshared is the libshared.so library that is compiled using the following command:

clang -shared -o libshared.so main.o -L/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/macosx

Notice the main.o, this got produced using the following command:

swiftc main.swift -emit-object

Thanx for the hints

Upvotes: 3

Related Questions