Search code examples
androidioskotlin-multiplatform

Is it possible to use a native library with platform-specific dependencies in a common KMP module?


My application uses the native library A. It is built as A.so for Android and A.framework for iOS and has the same codebase on both platforms. This library depends on another native library B, which is built into B.so and B.framework for Android and iOS. Library B has the same interface, but is implemented differently on platforms and uses iOS and Android APIs.

I would like to make a module that would encapsulate libraries A and B and provide some kind of unified interface for working with them. In the future I want to use this module in a KMP application.

Can I assemble A and B into one common KMP module that can be used from both platforms?

I searched for similar questions but didn't find anything. There have been many questions asking how to use native libraries with KMP, but in those cases the libraries were the same for all targets and did not have a platform-specific API.


Solution

  • Yes, this is absolutely possible, but as you can probably imagine, there are several moving parts involved.

    I gave a talk about this last year. The website hosting the video mislabeled it, but the talk is about bridging native code for KMP. I intentionally skip configuring JNI, but if you already do that, you can write a common layer that delegates to both, and the talk discusses how to add the native side.

    https://www.droidcon.com/2022/06/28/sdk-design-and-publishing-for-kotlin-multiplatform-mobile/

    For a public example of doing this, see Zipline from the CashApp team. They are building C for both platforms, and using JNI on Android and cinterop on iOS to talk to them. They are using one of our libraries on the native side to package the C binaries as a library, which you may not need, but it does make distribution much easier (see cklib).

    For an example of mounting native libs and writing a common interface layer, we do that for both Crashlytics and Bugsnag with CrashKiOS. Just FYI, we are currently wrestling with a linker issue when Kotlin builds native tests. This is because we don't want to include the native dependencies directly in the library build, but you may not have that issue.