Flutter / Dart FFI existing .so file for Android

2.7k Views Asked by At

I'm trying to use a pre-compiled .so file with Flutter/Dart FFI.

I've generated bindings with dart-ffigen, which seems to work without any issues.

I've added the following to the build.gradle file within the android block.

    externalNativeBuild {
        // Encapsulates your CMake build configurations.
        cmake {
            // Provides a relative path to your CMake build script.
            path "CMakeLists.txt"
        }
    }

CMakeLists.txt:

cmake_minimum_required(VERSION 3.4.1)  # for example

find_library( stl_android
             ../ios/Classes/libstl.so )

add_library( stl_android SHARED IMPORTED )

I've also tried the cmakelists.txt file that is documented on the FFI page, but that gives an exception related to it not knowing the language of the .so file. I'm assuming that's because it is an compiled library, not sourcecode.

In Dart I use the following code:

Platform.isAndroid
        ? DynamicLibrary.open('libstl.so')
        : DynamicLibrary.process();

But this gives the following exception:

Invalid argument(s): Failed to load dynamic library 'libstl.so': dlopen failed: library "libstl.so" not found

I'm not entirely sure what I'm doing wrong here, I'm expecting something in the makelist file to be wrong.

1

There are 1 best solutions below

2
On

I've solved this issue by using this CMakeLists.txt

add_library(
        stl_android
        SHARED
        IMPORTED
        GLOBAL
)
set_target_properties(stl_android PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/src/main/jniLibs/${ANDROID_ABI}/libstl.so)

The .so files need to be added in the following directory:

  • android/app/src/main/jniLibs/arm64-v8a
  • android/app/src/main/jniLibs/armeabi-v7a
  • android/app/src/main/jniLibs/x86
  • android/app/src/main/jniLibs/x86_64

and any other platform you might want to support.

The .so files need to be compiled for the correct targets of course.