Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Kotlin C Interop

Kotlin C Interop

Kotlin is a great language! But what if you want to call an existing native library in Kotlin, or build your own native library for performance optimizations? This is also useful for making Kotlin a viable option for systems programming. Perhaps there’s an existing C or C++ library that would be great to have available in Kotlin, but it isn’t yet Kotlin-ready? We’ll take a look at how to access native libraries with Kotlin.

Matt Moore

August 23, 2019
Tweet

More Decks by Matt Moore

Other Decks in Programming

Transcript

  1. Kotlin C Interop Matt Moore github: mattmoore twitter: mattmoore_io kotlinlang

    slack: mattmoore medium: mattmoore_io Rally Health https://www.builtinchicago.org/company/rally-health
  2. Let's Build A C Library Step 1: greeter.h Step 2:

    greeter.c Step 3: Compile libgreeter.dylib
  3. C-Interop for Kotlin Native • When you want to use

    the Kotlin language without the JVM • Easier working with other native modules (system libraries in C/C++) • System programming - C/C++/Golang can be painful!
  4. C-Interop for Kotlin Native cinterop Step 1: Create def file

    for library you want to use Step 2: Run cinterop to generate Kotlin library "libgreeter.klib" Step 3: Import "libgreeter.klib" into Kotlin program
  5. Kotlin JVM: JNI (Java Native Interface) • Need another C

    library libgreeter_jni.dylib to translate between the JVM and libgreeter.dylib • Load libgreeter_jni.dylib in Kotlin JVM project
  6. Kotlin JVM: JNI Conversion Library Step 3: Compile C code

    in "hello_jni.c" to shared library "libhello_jni.dylib"
  7. Kotlin JVM: Using JNI Conversion Library Step 5: Call "hello()"

    native function
 in Main.kt Step 4: Create Kotlin C-Interop class "Greeter.kt" Step 6: Compile + Run Greeter.jar
  8. How to Find Me Code/docs for this talk: https://github.com/mattmoore/kotlin-cinterop-talk Kotlin

    C-Interop: https://kotlinlang.org/docs/reference/native/c_interop.html Kotlin Native Overview: https://kotlinlang.org/docs/reference/native-overview.html Java Native Interface (JNI): https://medium.com/@mattmoore_io/kotlin-jni-for- native-code-835e93af7ddf Matt Moore Resources github: mattmoore twitter: mattmoore_io kotlinlang slack: mattmoore medium: mattmoore_io