kotlinjava-native-interface

How to call a static JNI function from Kotlin?


It wouldn't be a problem in Java but in Kotlin, we don't have static. We have companion objects for the same purpose, however, being extra objects, they get a mangled name in JNI calls (Java_package_Type00024Companion_function) and this doesn't match up with what JNI expects. Calling it from the main class, obviously, results in a JNI error in GetStaticMethodID.


Solution

  • The @JvmStatic annotation can be added to the function defined on the companion object to cause the generation of a static method which you can refer to in you jni calls.

    From the linked kotlin docs:

    class C {
      companion object {
        @JvmStatic fun callStatic() {}
        fun callNonStatic() {}
      }
    }
    
    // java
    C.callStatic(); // works fine
    C.callNonStatic(); // error: not a static method