In order to invoke a JNI we need to create a Kotlin class with extrenal method and a C function with specific signature for each external method in Kotlin.
Let’s assume that we have the following class in Kotlin:
package hr.com.unix.kotlin.jni.example
class ExampleJNI {
companion object {
init {
// We could also use System.loadLibrary if we package lib in jar
System.load("/path/to/cmake-build-debug/libExampleJNI.so")
}
}
external fun add(a: Int, b: Int): Int
}
For this to work, we will need to create CMake C++ project with following CMakeLists.txt config:
cmake_minimum_required(VERSION 3.25)
project(ExampleJNI)
set(CMAKE_CXX_STANDARD 17)
add_library(ExampleJNI SHARED
main.cpp
)
target_include_directories(ExampleJNI PUBLIC
/usr/lib/jvm/java-17-openjdk-amd64/include
/usr/lib/jvm/java-17-openjdk-amd64/include/linux
)
the function with following main.cpp file:
#include <iostream>
#include "jni_md.h"
#include "jni.h"
extern "C" {
jint Java_hr_com_unix_kotlin_jni_example_ExampleJNI_add(
JNIEnv *env,
jobject obj,
jint a,
jint b
) {
return a + b;
}
}