Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling functions from native compiled shared library on Android with Flutter

I have followed the instructions at https://flutter.dev/docs/development/platform-integration/c-interop and have successfully compiled cpp with a c abi and called it with the dart:ffi on an emulated android device using the CMake integration. This compiles an lib*.so file, copies it over with the flutter package and places it so I can reach it easily in my flutter code.

However, assume I already have a compiled shared library either compiled myself or gotten somewhere that works with Android and its given cpu architecture outside using CMake.

How do I add it to the flutter system so its copied over and placed in a "resolvable" location the same way its done when adding

android {
 //...
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
}

adds the target in the CMake files with the package?

For details I have compiled an shared library in rust with cargo-ndk and the correct achitecture, but I only get errors when trying to open it with `ffi.DynamicLibrary.open(...), no matter what I have tried.

I am guessing its something stupidly simple, but I can't figure out a way.

My dart ffi.DynamicLibrarycode linking against the library native on Windows works without problem. So it seems to be mainly a Android/flutter/gradle packaging issue.

like image 504
trondhe Avatar asked Mar 04 '23 03:03

trondhe


1 Answers

To add your precompiled shared library, you need to put it in android/app/src/main/jniLibs/X folder, where X is architecture name (armeabi-v7a or arm64-v8a). Though it's default path for libraries, I'm not completely sure if it's necessary, but it's probably safer to specify this folder as a source set in build.gradle:

android {
    sourceSets {
        main {
            jniLibs.srcDirs = ['src/main/jniLibs']
        }
    }        
}

After that you should be able to load it using Dart's DynamicLibrary.open and Java's System.loadLibrary.

like image 177
Igor Kharakhordin Avatar answered Mar 06 '23 10:03

Igor Kharakhordin