SwiftAndroid / swift

Port of Apple's reference Swift toolchain to Android; doesn't quite work yet

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Current status in NDK usage?

avaidyam opened this issue · comments

This isn't so much an issue as it is a usage question:

I have a small Swift framework that I'd rather not port into Java. It's only using NSObject for the setValue:forKey: magic, and that could be easily replaced. If it's written in pure Swift, how would I interface it from the Java side of things?

Currently @ephemer is working on https://github.com/SwiftAndroid/swift-jni, which allows access to Java JNI. Then, one can write wrapper functions that convert JNI arguments to/from native Swift datatypes, and use them as native methods from Java. A very simple proof of concept can be found at https://github.com/SwiftAndroid/swift-android-samples/blob/master/swifthello/src/main/swift/Sources/main.swift

I would suggest that you also look at other projects for Swift on Android if you don't need full compatibility with the reference toolchain, such as the (more mature) RemObjects Silver.

The problem is that I do need compatibility with the reference toolchain. I'll take a look at the other projects; thanks for the info!

What do you mean exactly by compatibility?

@zhuowei has made a gradle plugin that will compile your swift code alongside other native code. Personally I've just used swiftc-android to build shared libraries which can be loaded / linked against by any other native come you compile (regardless of toolchain)

Either way you'll very likely have to deal with the JNI/NDK, unless you use RemObjects Silver or the like (which may or may not have its own issues- I don't know how it works under the hood, I did read some question marks re: Arrays being passed by reference rather than by value, but I suspect the actual issues there will be more along the lines of interfacing with other native / Java code down the line)

@ephemer @zhuowei So if I have a pure Swift project, understandably I would end up dealing with the JNI or NDK (which is C++, so how is Swift doing that?). Is there a way for me to expose all the library functions/classes/structs to the Java side of things and call them directly?

@avaidyam, you expose certain top-level (non-class) functions to Java, currently using some undocumented (but very easy to use) compiler features. In a nutshell, that is what the JNI does.

Maybe I'm missing something but from what I can see the JNI and NDK have C (in addition to C++) APIs, which is no problem for Swift. What I've done is wrap those C APIs to make them look closer to their C++ equivalents and more idiomatically "Swift-like" in their usage.

@ephemer Got it, thanks! 👍