我正在尝试在Android设备上原生使用C++构建Tensorflow lite。我为每种体系结构构建了一个.so tensorflow 文件,并将其放置在jniLibs文件夹中。这是我的Cmake文件:

set(pathToProject /ih/user/project/NativeTfLite/app)

set(libs ${pathToProject}/src/main/jniLibs)
add_library(libtensorflowLite SHARED IMPORTED
        )
set_target_properties(libtensorflowLite PROPERTIES IMPORTED_LOCATION
        ${libs}/${ANDROID_ABI}/libtensorflowLite.so)

find_library(
        log-lib
        log )

add_library(
        native-lib
        SHARED
        native-lib.cpp)

target_include_directories(native-lib PRIVATE
        ${lib}/include)

target_link_libraries( # Specifies the target library.
        native-lib.     #Problem is here when linking native-lib with libtensorflowlite
        libtensorflowLite
        ${log-lib} )


在编译期间,将找到这些文件。但是,在target_link_libraries行中,两个库libtensorflowlite和native-lib的链接存在运行时崩溃,并出现以下错误:

java.lang.UnsatisfiedLinkError:dlopen失败:未找到库“/Users/ih/project/cameraFrames/NativeTfLite/app/src/main/jniLibs/arm64-v8a/libtensorflowLite.so”

此外,.SO文件未链接到APK。

这是我的build.gradle文件:


apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"

    defaultConfig {
        applicationId "com.proj.nativetflite"
        minSdkVersion 24
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        sourceSets {
            main {
                jniLibs.srcDir 'src/main/jniLibs'
                jniLibs.srcDirs = ["src/main/jniLibs"]
            }
        }
        externalNativeBuild {
            cmake {
                cppFlags "-std=c++11"
                arguments '-DCMAKE_VERBOSE_MAKEFILE=ON'
            }
        }
        ndk {
            abiFilters  "armeabi-v7a", "x86" , "arm64-v8a"
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    externalNativeBuild {
        cmake {
            path "src/main/cpp/CMakeLists.txt"
            version "3.10.2"
        }
    }
}

dependencies {
    implementation fileTree(dir: 'jniLibs', include:  '**/*.so')

    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

是什么原因造成的?

最佳答案

在AGP 4.0之前,您需要使用jniLibs:https://developer.android.com/studio/projects/gradle-external-native-builds#jniLibs显式打包预构建的库。请注意,文档说您不需要对CMake声明的任何内容执行此操作,但是我敢肯定,这里的文档是错误的(我已经联系文档所有者以查看是否需要修复此问题,因为它适用于4.0)。

在4.0中应该没有必要,但是还没有达到稳定。

08-05 21:00