10

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.

3 Answers 3

12

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
2
  • Wonderful. I was trying to look for an annotation to modify the JNI name at will but that didn't work (it only changes the actual function name, not the whole caboodle) but I've missed this one. Thanks.
    – Gábor
    Commented Jul 19, 2019 at 18:44
  • Wasted 2 hours in limbo land on this. I pasted Java JNI methods which Android Studio auto-converted to Kotlin but minus this @JvmStatic thing.
    – daparic
    Commented Sep 24, 2020 at 9:08
1

Use external keyword in kotlin.

external fun nativeKey1() : String?

keys.c class:

Java_com_mobile_application_MyApplication_00024Companion_nativeKey1(
    JNIEnv *env, jobject thiz) {
static const char randomStr[] = "89!Q4q+x#f6~iOL9@&c>2JY!s!x@2Ai-SbHYA@EenokBTE#NoTiE6jl4-5zovso@2Ai-SbHYAEenokBNoTiE6jl4SbHYA@EenokBTE";
char key[17] = {0};

// Start garbage code
int i = 0;
float j = 0;
int loop_count = 0;

for (i=0; i < loop_count; i++) {
    int n = (i / 2) + 29 + i + 17;
    key[0] = randomStr[n];

}

0

A workaround would be to create a wrapper in Java and use that from Kotlin.

1
  • 1
    I can't see how that would help me. All these JNI functions are called from a specific class (the implementation expects this type name). Either I do the whole class in Java or in Kotlin. I can't mix the two à la C#, have partial class declarations, let alone in two languages.
    – Gábor
    Commented Jul 19, 2019 at 18:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.