首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在资源路径(.)中找不到本机库(com/sun/jna/android/libjniDispatch.so)

在资源路径(.)中找不到本机库(com/sun/jna/android/libjniDispatch.so)
EN

Stack Overflow用户
提问于 2022-10-26 11:44:59
回答 1查看 72关注 0票数 1

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

代码语言:javascript
复制
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和一个包含/testproject.h的头文件。

这两种功能都只包含一些小功能(仅用于复制我的错误)。

代码语言:javascript
复制
// testproject.c
#include <stddef.h>
#include <stdlib.h>
#include "../include/testproject.h"

int testFunc() {
    return 15;
}
代码语言:javascript
复制
// testproject.h
int testFunc();

我想使用JNA在c和Java之间架起桥梁。我的正在工作。但是,当我调用库函数testFunc()时,我会收到以下错误消息:

代码语言:javascript
复制
Could not invoke JavaCaller.getLib
null
Native library (com/sun/jna/android-aarch64/libjnidispatch.so) not found in resource path (.)

我的项目结构如下:

代码语言:javascript
复制
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"

我在我的TestLib.java中加载了我的库

代码语言:javascript
复制
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();
}

并在我的testFunc()中调用TestCaller.java

代码语言:javascript
复制
public class TetsCaller extends ReactContextBaseJavaModule {
   ...
    @ReactMethod
    public void getLib(Callback callback) {
        int test = TestLib.INSTANCE.testFunc();
        callback.invoke(test);
        return;
    }
   ...
}

还有我的app/build.gradle文件

代码语言:javascript
复制
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时遗漏了什么吗?我是否必须在我的exclude文件中加入jna?我认为我的动态库和我的调用似乎很好,所以这个错误必须在我的gradle文件中或者在任何地方设置一个错误的路径。

此外,从我在build.gradle中看到的情况来看,from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")行中引用的行目录似乎是空的。

编辑:

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

Edit2:

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

Edit3:

正如Daniel 所指出的,安卓-*文件夹/jar文件不包括在当前提供的jna.jar中,因此我下载了它们,在jna.jar中创建了相应的文件夹,并添加了它们(仅包括libjnidispatch.so)。因为我在我的gradle中使用了implementation files('libs/jna.5.12.1.jar'),所以应该从jar中选择它们。我还创建了文件夹aarch64android-aarch64,包括libjnidispatch.so,但错误仍然不断出现。我想这是我的路设置好了,但我不知道在哪里。

另外,在我的gradle中使用implementation 'net.java.dev.jna:jna:5.12.1并注释掉implementation files(...)并不能解决这个问题。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-28 07:12:25

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

代码语言:javascript
复制
implementation files('libs/jna.5.12.1.jar@aar')
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74207214

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档