Slide 1

Slide 1 text

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

Slide 2

Slide 2 text

C Interop on Two Platforms • Kotlin Native • Kotlin JVM

Slide 3

Slide 3 text

Let's Build A C Library Step 1: greeter.h Step 2: greeter.c Step 3: Compile libgreeter.dylib

Slide 4

Slide 4 text

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!

Slide 5

Slide 5 text

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

Slide 6

Slide 6 text

Create C-Interop Kotlin Native Library Step 2: Compile Kotlin library "libgreeter.klib" Step 1: libgreeter.def

Slide 7

Slide 7 text

Using libgreeter.klib Step 2: Compile Step 1: Main.kt

Slide 8

Slide 8 text

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

Slide 9

Slide 9 text

Kotlin JVM: JNI Conversion Library Step 1: greeter_jni.h

Slide 10

Slide 10 text

Kotlin JVM: JNI Conversion Library Step 2: greeter_jni.c

Slide 11

Slide 11 text

Kotlin JVM: JNI Conversion Library Step 3: Compile C code in "hello_jni.c" to shared library "libhello_jni.dylib"

Slide 12

Slide 12 text

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

Slide 13

Slide 13 text

program.kexe libgreeter.klib libgreeter.dylib java -jar -Djava.library.path=/usr/local/lib build/Greeter.jar libgreeter_jni.dylib libgreeter.dylib Kotlin Native ~ vs ~ Kotlin JVM libgreeter_jni.h libgreeter_jni.c libgreeter.def

Slide 14

Slide 14 text

Kotlin Native Kotlin JVM

Slide 15

Slide 15 text

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