https://kotlinlang.org logo
Title
m

Marcus Cvjeticanin

04/14/2023, 9:05 PM
Anyone got good advice regarding usage of an already existing C Library with Kotlin. What is the most convenient way to set this up? Should I use JNI or multiplatform? I'm building basically a library which will have some cryptographic library that I will use in my code. JNI seems pretty tedious to setup tbh.
c

Casey Brooks

04/14/2023, 9:15 PM
You’ll need to set up the bindings individually for each target you plan on supporting. Kotlin Multiplatform compiles the common Kotlin source for each target platform, but it doesn’t enable you to run libraries from one platform/language on another. It won’t allow you to use Java libraries on iOS, for example, nor will it allow you to directly use C libraries in any target without some manual effort to set up the bindings. If you’re supporting JVM targets, you’ll need to set up JNI. If you’re targeting Native, you would use cinterop.
m

Marcus Cvjeticanin

04/14/2023, 9:16 PM
Ah ok! Dumb question, if a Kotlin Native project will use my library. How will that function? WIll it work if I use JNI?
c

Casey Brooks

04/14/2023, 9:25 PM
No. JNI is a strictly Java platform feature. Kotlin Native does not run on the Java platform (JVM), but produces its own native binaries, similar to how C itself produces native code when compiled. When Kotlin compiles to JVM targets (plain JVM or Android) it can use all of the features of the Java platform, like JNI, Java libraries, and it runs in the JVM. But when Kotlin compiles code to Native, like on iOS, it cannot use any Java features, because it’s not trying to run Java code on a different native platform. It’s using an entirely different set of tooling (LLVM) to compile Kotlin source code to a different format. In a similar way, when Kotlin compiles for JS targets, the output is literally just Javascript, and it uses Webpack and other Node-JS based tooling to compile Kotlin code for JS.
e

ephemient

04/14/2023, 9:57 PM
there's nothing Kotlin-specific about JNI (or any of its alternatives like JNA and JNR)
https://jdk.java.net/panama/ has been available in preview since Java 19, which will a better alternative to JNI for most uses (on JVM)