mercredi 23 février 2022

Load Android Native library with Java reflection

I'm trying to load an Android native library with Java reflection, but at runtime the library is not found. Normally i load a native library with:

System.loadLibrary("mylib");

and everything works as expected. Now i try to call the loadLibrary method with reflection, like this:

Class<?> system = Class.forName("java.lang.System");
Method loadLibrary = system.getDeclaredMethod("loadLibrary", String.class);
loadLibrary.invoke(null, "mylib");

but at runtime i get:

Caused by: java.lang.UnsatisfiedLinkError: Library mylib not found; tried [/system/lib64/libmylib.so, /vendor/lib64/libmylib.so]
    at java.lang.Runtime.loadLibrary0(Runtime.java:1001)
    at java.lang.System.loadLibrary(System.java:1530)
    at java.lang.reflect.Method.invoke(Native Method)

It seems like with reflection loadLibrary look for the library in the wrong path. These /system/lib64:/vendor/lib64 are the paths of java.library.path property, but it does not look inside the apk. Of course the library is present in the final apk, and it's in the right place, for the right ABI.

NOTE

I can't use

System.load("absolute-path-to-lib/mylib.so");

because from where i'm calling this i don't have the path available, i don't have any Context or Application available yet to retrive the path.

Do you have any idea how to force loadLibrary to search in the current apk ? Thank you!





Aucun commentaire:

Enregistrer un commentaire