Compile kotlin module to C using Kotlin Multiplatform

Hi,

I am looking in to writing a kotlin library/module for Android which I would like to re-use windows/macOS/Linux. My concern is that can I compile this library as a module in C so that the desktop platforms can use it? I am new to Kotlin multiplatform and any feedback is much appreciated.

Thanks

Hey there! It sounds like kotlin multiplatform should serve your use case well. The way it works is you can configure either common or platform specific modules through Gradle and then specify compile targets for each module.

Most likely you would want to keep most of your code in a common module which is compiled as both an Android library (published via maven repo or otherwise) as well as a .so, .dylib, or .dll, depending on what native desktop app platform you want to include your code in. If you need some functions in the common module to access platform specific APIs, you can do that too. Kotlin multiplatform allows you to define “expect” functions or classes in your common code, then define the actual implementation in “actual” functions or classes in other platform specific Gradle modules that the common module depends on. For example, in common code you could have a “save image” function which is an “expect fun” in your common code, then use Android APIs to open an Android file picker or something in an Android Kotlin/JVM module that the common module depends on. In your native module, you might invoke a windows file picker API in a Windows Kotlin/Native module that the common module depends on.

It’s all very flexible, and while I don’t have much experience configuring Gradle to do this I at least get the concepts and hope this helped. Note that when building native libraries I’m pretty sure you have to run the Gradle build on the appropriate platform (so you need windows to build a .dll, Mac for .dylib, etc.). To my knowledge cross compilation isn’t supported by kotlin native at the moment.