https://kotlinlang.org logo
#kotlin-native
Title
# kotlin-native
d

Dmytro Serdiuk

10/05/2023, 5:44 PM
Hello! I have a question about Kotlin/Native. Is cinterop and JNI is the same tools for importing C/C++ code into kotlin/native code? As I understand, cinterop creates Kotlin code to access the native implementation, while JNI is tool to load lib and write your mappings manually? Thanks
a

Adam S

10/05/2023, 10:42 PM
I'll try and give a brief summary that I hope explains! Kotlin can be compiled to different targets: JVM, Native, JavaScript, and Wasm. While some Kotlin code can be shared between the targets, often you'll have to write target-specific Kotlin code. For example, you can't use Java's LocalDateTime when targeting JavaScript or Native or Wasm - so you'll have to use something else (like kotlinx-datetime) When targeting JVM, Kotlin can seamlessly use, and be used by, Java code. JNI is a Java-specific tool for calling C code (or some C++ code, I think?) from Java or Kotlin/JVM - but you'll have to write the bindings manually. Because JNI is a Java tool, it can be used by Kotlin, but only Kotlin/JVM. AFAIK there's no automated JNI generator, which is very annoying (but watch this space!). Kotlin cinterop is basically like JNI, except it's specifically only for Kotlin/Native. It's a bit nicer because it can automatically generate C bindings, so you can call C libraries from Kotlin/Native code. It's kind of like the equivalent of how Kotlin/JVM can automatically interop with Java code, except more lower level, experimental, and C-specific. So.... > Is cinterop and JNI is the same tools for importing C/C++ code into kotlin/native code? > No. They're similar, but JNI is JVM only, cinterop is Native only. > As I understand, cinterop creates Kotlin code to access the native implementation, while JNI is tool to load lib and write your mappings manually? > Yes. Although cinterop often requires some wrangling, so there's some friction.
d

Dmytro Serdiuk

10/06/2023, 12:02 AM
Thank you very much for the explanation!
6 Views