Search code examples
androidxamarin.androidjava-native-interface

JNIEnv FindClass() can't find package/Class that is part of a Xamarin Android Binding Library


I'm trying to call a Kotlin function from C++ via the JNI.

The Kotlin function is in a class that is part of an Android Binding library, attached to a Xamarin app.

The C++ code is in a native library of the same Xamarin app.

I call FindClass() with this line of code:

 jclass classObj = m_env->FindClass("de/companyname/packagename/MyKotlinClass");

m_env is a valid pointer to the JNI environment (for example, I can find standard Java library classes successfully). The above line of code fails with

java.lang.ClassNotFoundException: Didn't find class "de/companyname/packagename/MyKotlinClass" on path: DexPathList[[directory "."],nativeLibraryDirectories=[/vendor/lib, /system/lib]]

In the classes.dex file of the signed apk, I can see MyKotlinClass with the correct path. But somehow the JNI can't find it.

Is this because the Kotlin class is part of an AAR that is included in an Android Binding Library? What can I do to make JNI find my class?


Solution

  • I found a solution, by calling FindClass() from C++ code that is included inside the AAR in the Android Binding Library. I can then call this C++ from my main C++ module using dlopen.

    This is a good solution for me, because I control the contents of the AAR. If you have a third party AAR, I think it would also work if you added a separate C++ .so file to your Android Binding Library, but I haven't tested that scenario.