UnsatisfiedLinkError in companion object Kotlin JN

2020-05-05 17:28发布

问题:

I'm converting code from Java to Kotlin in one of my mobile apps, and the code that worked in Java stopped working in Kotlin. It uses JNI bridge to call C++ code.

Kotlin method declaration:

class Converter{  
    companion object {
        external fun convertNative(width: Int, height: Int, row: Int, input: ByteArray, ft: Int, output: ByteArray)
    }
}

.cc code:

   extern "C" {
    JNIEXPORT void JNICALL OBJECT_TRACKER_METHOD(convertNative)(JNIEnv* env, jobject thiz, jint width, jint height, jint row,
    jbyteArray input, jint ft, jbyteArray output);
}
    JNIEXPORT void JNICALL OBJECT_TRACKER_METHOD(convertNative)(
    JNIEnv* env, jobject thiz, jint width, jint height, jint row,
    jbyteArray input, jint ft, jbyteArray output) {...}

the error I get:

java.lang.UnsatisfiedLinkError:No implementation found for void com.sampleapp.Converter$Companion.convertNative(int,int,int,byte[],int,byte[])(tried Java_com_sampleapp_Converter_00024Companion_convertNative and Java_com_sampleapp_Converter_00024Companion_convertNative__III_3BI_3B) at com.sampleapp.Converter$Companion.convertNative(Native Method)...

The original JAVA method (this works fine)

protected static native void convertNative(
      int width, int height, int row, byte[] input, int ft, byte[] output);

Also the library is properly loaded using System.loadLibrary (I see correct log output, no errors) in both cases.

回答1:

If you want to avoid changing the C++ code you should annotate the Kotlin function with @JvmStatic, i.e:

@JvmStatic external fun convertNative(width: Int, height: Int, row: Int, input: ByteArray, ft: Int, output: ByteArray)

By the way, your C++ function declaration is technically incorrect: For static methods, the second parameter is a jclass, not a jobject.