When using Rust libraries with flutter_rust_bridge on Android, you may encounter these errors:
- Missing libc++_shared.so:
Failed to load dynamic library 'librust_lib_flick_player.so':
dlopen failed: library "libc++_shared.so" not found
- Android context not initialized (when using cpal/oboe):
PanicException(android context was not initialized)
The Rust library (via cpal with oboe-shared-stdcxx feature) requires libc++_shared.so from the Android NDK, but this library is not automatically included in the APK.
When using cpal with Oboe for audio on Android, the NDK context must be initialized before the library is loaded. This requires loading the native library from the Java/Kotlin side before Dart loads it.
We've implemented an automated solution that copies libc++_shared.so from the Android NDK to the app's jniLibs directory during the build process.
-
android/app/build.gradle.kts
- Added
sourceSetsconfiguration to include jniLibs - Added
pickFirstsforlibc++_shared.soto handle duplicates - Added
copyNdkLibstask that runs beforepreBuild
- Added
-
android/copy_ndk_libs.sh
- Script that copies
libc++_shared.sofrom NDK to jniLibs for all ABIs - Automatically detects NDK location from
ANDROID_NDK_HOMEorANDROID_HOME - Supports multiple NDK versions and directory structures
- Script that copies
For cpal/oboe to work, we need to initialize the NDK context before Dart loads the library.
-
rust/Cargo.toml
- Added
jniandndk-contextdependencies for Android target
- Added
-
rust/src/lib.rs
- Added
JNI_OnLoadfunction to initialize NDK context when library is loaded
- Added
-
android/app/src/main/kotlin/.../MainActivity.kt
- Added
initblock to load the Rust library before Dart does - This ensures
JNI_OnLoadis called and NDK context is initialized
- Added
The libc++_shared.so library is now automatically copied during the build:
flutter build apk --flavor full # or --flavor play
# or
flutter build appbundle --flavor play # or --flavor fullIf you need to manually copy the libraries:
./android/copy_ndk_libs.sh- arm64-v8a (64-bit ARM)
- armeabi-v7a (32-bit ARM)
- x86_64 (64-bit Intel)
- x86 (32-bit Intel)
- Android NDK must be installed
ANDROID_HOMEorANDROID_NDK_HOMEenvironment variable must be set
After building, verify the libraries are included:
find android/app/src/main/jniLibs -name "*.so"You should see libc++_shared.so for each ABI.