java 在资源路径(.)中未找到本机库(com/sun/jna/android-arm/libjnidispatch.so)

epfja78i  于 2022-10-30  发布在  Java
关注(0)|答案(1)|浏览(150)

在我的android应用程序中,我想从我的动态库(.so)中调用c/c++代码,我使用以下CMakeLists.txt构建了这个库

cmake_minimum_required(VERSION 3.1)
project(testproject)

# Use C++ 11 by default

set(CMAKE_CXX_STANDARD 17)

# Set Release as default build type

if (NOT CMAKE_BUILD_TYPE)
    set(CMAKE_BUILD_TYPE Release)
endif (NOT CMAKE_BUILD_TYPE)

# find header & source

file(GLOB_RECURSE SOURCE_C "src/*.c")
file(GLOB_RECURSE HEADER "include/*.h")

add_library(${PROJECT_NAME}  SHARED
  ${SOURCE_C}
  ${HEADER}
)

# includes

include_directories( /include )
target_include_directories(${PROJECT_NAME}  PUBLIC ${CMAKE_CURRENT_LIST_DIR}/include)

source_group("Header include" FILES ${HEADER})
source_group("Source src"     FILES ${SOURCE_C})

在这个伪库中,我只有一个c文件src/testproject. c和一个包含在include/testproject. h中的头文件
两者都只包含次要功能(仅用于重现我的错误)
第一个
我想使用JNA在C和Java之间建立桥梁。我的Java-ReactNative连接正常工作。但是当我调用库函数testFunc()时,收到以下错误消息:

Could not invoke JavaCaller.getLib
null
Native library (com/sun/jna/android-aarch64/libjnidispatch.so) not found in resource path (.)

我的项目结构如下:

android-app-src-main-java-com-devname-projectname-JavaCaller.java
             |         |                           |
             |         |                       TestLib.java
             |         |
             |      jniLibs-libtestproject.so
             |         |
             |    "android-aarch64"-libjnidispatch.so
             |         |
             |      aarch64-libjnidispatch.so
             |
           libs-"jna-5.12.1.jar"

我在我的www.example.com中加载我的库TestLib.java

package com.devname.projectname;
import com.sun.jna.Library;
import com.sun.jna.Native;

public interface TestLib extends Library{
    TestLibINSTANCE = (TestLib) Native.loadLibrary("testproject", TestLib.class);
    int testFunc();
}

并调用我的www.example.com中的testFunc()TestCaller.java

public class TetsCaller extends ReactContextBaseJavaModule {
   ...
    @ReactMethod
    public void getLib(Callback callback) {
        int test = TestLib.INSTANCE.testFunc();
        callback.invoke(test);
        return;
    }
   ...
}

还有我的app/build.gradle文件

apply plugin: "com.android.application"

import com.android.build.OutputFile
import org.apache.tools.ant.taskdefs.condition.Os

def projectRoot = rootDir.getAbsoluteFile().getParentFile().getAbsolutePath()

def reactNativeRoot = new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath()

project.ext.react = [
    entryFile: ["node", "-e", "require('expo/scripts/resolveAppEntry')", projectRoot, "android"].execute(null, rootDir).text.trim(),
    enableHermes: (findProperty('expo.jsEngine') ?: "jsc") == "hermes",
    hermesCommand: new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath() + "/sdks/hermesc/%OS-BIN%/hermesc",
    cliPath: "${reactNativeRoot}/cli.js",
    composeSourceMapsPath: "${reactNativeRoot}/scripts/compose-source-maps.js",
]

apply from: new File(reactNativeRoot, "react.gradle")

def enableSeparateBuildPerCPUArchitecture = false

/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = (findProperty('android.enableProguardInReleaseBuilds') ?: false).toBoolean()

def jscFlavor = 'org.webkit:android-jsc:+'

def enableHermes = project.ext.react.get("enableHermes", false);

/**
 * Architectures to build native code for.
 */
def reactNativeArchitectures() {
    def value = project.getProperties().get("reactNativeArchitectures")
    return value ? value.split(",") : ["armeabi-v7a", "x86", "x86_64", "arm64-v8a"]
}

android {
    sourceSets {
        main {
            jniLibs.srcDir(['src/main/jniLibs'])
        }
    }

    packagingOptions {
        pickFirst 'lib/x86/libc++_shared.so'
        pickFirst 'lib/x86_64/libc++_shared.so'
        pickFirst 'lib/armeabi-v7a/libc++_shared.so'
        pickFirst 'lib/arm64-v8a/libc++_shared.so'
    }
    ndkVersion rootProject.ext.ndkVersion

    compileSdkVersion rootProject.ext.compileSdkVersion

    defaultConfig {
        applicationId 'com.developername.projectname'
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0.0"
        buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
        // ndk {
        //     abiFilters 'linux-arm'
        // }

        if (isNewArchitectureEnabled()) {
            // We configure the NDK build only if you decide to opt-in for the New Architecture.
            externalNativeBuild {
                ndkBuild {
                    arguments "APP_PLATFORM=android-21",
                        "APP_STL=c++_shared",
                        "NDK_TOOLCHAIN_VERSION=clang",
                        "GENERATED_SRC_DIR=$buildDir/generated/source",
                        "PROJECT_BUILD_DIR=$buildDir",
                        "REACT_ANDROID_DIR=${reactNativeRoot}/ReactAndroid",
                        "REACT_ANDROID_BUILD_DIR=${reactNativeRoot}/ReactAndroid/build",
                        "NODE_MODULES_DIR=$rootDir/../node_modules"
                    cFlags "-Wall", "-Werror", "-fexceptions", "-frtti", "-DWITH_INSPECTOR=1"
                    cppFlags "-std=c++17"
                    // Make sure this target name is the same you specify inside the
                    // src/main/jni/Android.mk file for the `LOCAL_MODULE` variable.
                    targets "projectname_appmodules"

                    // Fix for windows limit on number of character in file paths and in command lines
                    if (Os.isFamily(Os.FAMILY_WINDOWS)) {
                        arguments "NDK_APP_SHORT_COMMANDS=true"
                    }
                }
            }
            if (!enableSeparateBuildPerCPUArchitecture) {
                ndk {
                    abiFilters (*reactNativeArchitectures())
                }
            }
        }
    }

    if (isNewArchitectureEnabled()) {
        // We configure the NDK build only if you decide to opt-in for the New Architecture.
        externalNativeBuild {
            ndkBuild {
                path "$projectDir/src/main/jni/Android.mk"
            }
        }
        def reactAndroidProjectDir = project(':ReactAndroid').projectDir
        def packageReactNdkDebugLibs = tasks.register("packageReactNdkDebugLibs", Copy) {
            dependsOn(":ReactAndroid:packageReactNdkDebugLibsForBuck")
            from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
            into("$buildDir/react-ndk/exported")
        }
        def packageReactNdkReleaseLibs = tasks.register("packageReactNdkReleaseLibs", Copy) {
            dependsOn(":ReactAndroid:packageReactNdkReleaseLibsForBuck")
            from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
            into("$buildDir/react-ndk/exported")
        }
        afterEvaluate {
            // If you wish to add a custom TurboModule or component locally,
            // you should uncomment this line.
            // preBuild.dependsOn("generateCodegenArtifactsFromSchema")
            preDebugBuild.dependsOn(packageReactNdkDebugLibs)
            preReleaseBuild.dependsOn(packageReactNdkReleaseLibs)

            // Due to a bug inside AGP, we have to explicitly set a dependency
            // between configureNdkBuild* tasks and the preBuild tasks.
            // This can be removed once this is solved: https://issuetracker.google.com/issues/207403732
            configureNdkBuildRelease.dependsOn(preReleaseBuild)
            configureNdkBuildDebug.dependsOn(preDebugBuild)
            reactNativeArchitectures().each { architecture ->
                tasks.findByName("configureNdkBuildDebug[${architecture}]")?.configure {
                    dependsOn("preDebugBuild")
                }
                tasks.findByName("configureNdkBuildRelease[${architecture}]")?.configure {
                    dependsOn("preReleaseBuild")
                }
            }
        }
    }

    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include (*reactNativeArchitectures())
        }
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            // Caution! In production, you need to generate your own keystore file.
            // see https://reactnative.dev/docs/signed-apk-android.
            signingConfig signingConfigs.debug
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // https://developer.android.com/studio/build/configure-apk-splits.html
            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }

        }
    }
}

// Apply static values from `gradle.properties` to the `android.packagingOptions`
// Accepts values in comma delimited lists, example:
// android.packagingOptions.pickFirsts=/LICENSE,**/picasa.ini
["pickFirsts", "excludes", "merges", "doNotStrip"].each { prop ->
    // Split option: 'foo,bar' -> ['foo', 'bar']
    def options = (findProperty("android.packagingOptions.$prop") ?: "").split(",");
    // Trim all elements in place.
    for (i in 0..<options.size()) options[i] = options[i].trim();
    // `[] - ""` is essentially `[""].filter(Boolean)` removing all empty strings.
    options -= ""

    if (options.length > 0) {
        println "android.packagingOptions.$prop += $options ($options.length)"
        // Ex: android.packagingOptions.pickFirsts += '**/SCCS/**'
        options.each {
            android.packagingOptions[prop] += it
        }
    }
}

dependencies {
    implementation 'net.java.dev.jna:jna:5.12.1'
    //noinspection GradleDynamicVersion
    implementation "com.facebook.react:react-native:+"
    implementation project(path: ':openCV')

    def isGifEnabled = (findProperty('expo.gif.enabled') ?: "") == "true";
    def isWebpEnabled = (findProperty('expo.webp.enabled') ?: "") == "true";
    def isWebpAnimatedEnabled = (findProperty('expo.webp.animated') ?: "") == "true";
    def frescoVersion = rootProject.ext.frescoVersion

    // If your app supports Android versions before Ice Cream Sandwich (API level 14)
    if (isGifEnabled || isWebpEnabled) {
        implementation "com.facebook.fresco:fresco:${frescoVersion}"
        implementation "com.facebook.fresco:imagepipeline-okhttp3:${frescoVersion}"
    }

    if (isGifEnabled) {
        // For animated gif support
        implementation "com.facebook.fresco:animated-gif:${frescoVersion}"
    }

    if (isWebpEnabled) {
        // For webp support
        implementation "com.facebook.fresco:webpsupport:${frescoVersion}"
        if (isWebpAnimatedEnabled) {
            // Animated webp support
            implementation "com.facebook.fresco:animated-webp:${frescoVersion}"
        }
    }

    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.fbjni'
    }
    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
        exclude group:'com.squareup.okhttp3', module:'okhttp'
    }
    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
    }

    if (enableHermes) {
        //noinspection GradleDynamicVersion
        implementation("com.facebook.react:hermes-engine:+") { // From node_modules
            exclude group:'com.facebook.fbjni'
        }
    } else {
        implementation jscFlavor
    }
}

if (isNewArchitectureEnabled()) {
    // If new architecture is enabled, we let you build RN from source
    // Otherwise we fallback to a prebuilt .aar bundled in the NPM package.
    // This will be applied to all the imported transtitive dependency.
    configurations.all {
        resolutionStrategy.dependencySubstitution {
            substitute(module("com.facebook.react:react-native"))
                    .using(project(":ReactAndroid"))
                    .because("On New Architecture we're building React Native from source")
            substitute(module("com.facebook.react:hermes-engine"))
                    .using(project(":ReactAndroid:hermes-engine"))
                    .because("On New Architecture we're building Hermes from source")
        }
    }
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.implementation
    into 'libs'
}

apply from: new File(["node", "--print", "require.resolve('@react-native-community/cli-platform-android/package.json')"].execute(null, rootDir).text.trim(), "../native_modules.gradle");
applyNativeModulesAppBuildGradle(project)

def isNewArchitectureEnabled() {
    // To opt-in for the New Architecture, you can either:
    // - Set `newArchEnabled` to true inside the `gradle.properties` file
    // - Invoke gradle with `-newArchEnabled=true`
    // - Set an environment variable `ORG_GRADLE_PROJECT_newArchEnabled=true`
    return project.hasProperty("newArchEnabled") && project.newArchEnabled == "true"
}

我在使用JNA时是否遗漏了一些东西?我是否必须在Gradle文件中使用exclude jna?我认为我的动态库和调用看起来很好,所以错误一定是在Gradle文件中,或者在任何地方设置了错误的路径。
另外,从我在build.gradle中看到的情况来看,from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")行中引用的行目录似乎是空的

编辑:

此外,jna已使用sudo apt-get install libjna-java安装。

编辑2:

我尝试通过修改jna.jar文件来从错误消息中重现路径com/sun/jna/android-aarch64/(重命名为.zip,然后再重命名为.jar)并复制linux-aarch64目录并将其重命名为android-aarch64。将jna.jar放入我的src/lib dir中,然后使用Android Studio添加它,行implementation 'net.java.dev.jna:jna:5.12.1'被替换为implementation group: 'net.java.dev.jna', name: 'jna', version: '5.12.1,错误仍然是相同的。即使文件现在应该在目录中。

编辑3:

正如丹尼尔Widdis所指出的,android-* 文件夹/jar文件不包括在当前提供的jna.jar中,因此我下载了它们,在我的jna.jar中创建了相应的文件夹并添加了它们(只包括libjnidispatch.so)。因为我在我的Gradle内部使用implementation files('libs/jna.5.12.1.jar'),我也创建了文件夹aarch64android-aarch64,包括libjnidispatch.so,但是错误仍然不断出现。我想这是我的路径设置的问题,但是我不知道在哪里。
此外,在我的Gradle中使用X1 M19 N1 X并注解掉X1 M20 N1 X并不能解决这个问题。

wgeznvg7

wgeznvg71#

在android上的app/build.gradle中使用implementation files('libs/jna.5.12.1.jar')需要将@aar添加到jar的末尾。

implementation files('libs/jna.5.12.1.jar@aar')

相关问题