android: `AndroidNativeLibrary` doesn't trigged `JNI_OnLoad`
Android application type
Classic Xamarin.Android (MonoAndroid12.0, etc.)
Affected platform version
VS 2022 17.4, Xamarin.Android 13.1.0.1
Description
I have a shared library (.so) written in C. The library exports JNI_OnLoad and JNI_OnUnload, confirmed with readelf:
478: 00000000002ff2f0 132 FUNC GLOBAL DEFAULT 13 JNI_OnLoad 3111: 00000000002ff380 297 FUNC GLOBAL DEFAULT 13 JNI_OnUnload
I reference the .so properly in my Xamarin.Android application using AndroidNativeLibrary.
However, at runtime JNI_OnLoad is never invoked.
Steps to Reproduce
See above
Did you find any workaround?
I can invoke JNI_OnLoad manually by first using reflection to get the java_vm pointer:
[DllImport("MyLibrary", CallingConvention = CallingConvention.Cdecl)]
private static extern int JNI_OnLoad(IntPtr vm, IntPtr reserved);
static MyClass()
{
var field = typeof(Android.Runtime.JNIEnv).GetField("java_vm", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
JNI_OnLoad((IntPtr)field.GetValue(null), IntPtr.Zero);
}
But this feels like an ugly workaround.
Relevant log output
N/A
About this issue
- Original URL
- State: open
- Created 4 years ago
- Reactions: 1
- Comments: 30 (17 by maintainers)
Commits related to this issue
- [Java.Interop] Use `Class.forName()` as fallback to load Java classes Fixes: https://github.com/dotnet/java-interop/issues/23 Context: https://github.com/dotnet/android/commit/aba272691f96fa179e7ea2... — committed to dotnet/java-interop by jonpryor 2 years ago
- [Java.Interop] Use `Class.forName()` as fallback to load Java classes (#1326) Fixes: https://github.com/dotnet/java-interop/issues/23 Context: https://github.com/dotnet/android/commit/aba272691f96fa... — committed to dotnet/java-interop by jonpryor 2 years ago
Thanks @jonpryor and @grendello for the support
@thenextman: I don’t think we’ll need your test project anymore. Confirmation that you’re using
System.Threading.Threadis sufficient.We think we understand the problem, but it’ll be some time before we can fix it. (Holidays!)
In the meantime, calling
JavaSystem.LoadLibrary()from the main/UI thread should allow your app to start.Thanks!