In my android app I want to call c/c code from my dynamic library (.so) I built with the following 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})
In this dummy library I only have a c-file src/testproject.c and a header inside of include/testproject.h
both only consist of minor functionalities (only for reproducing my error)
// testproject.c
#include <stddef.h>
#include <stdlib.h>
#include "../include/testproject.h"
int testFunc() {
return 15;
}
// testproject.h
int testFunc();
I want to use JNA to bridge between c and Java. My Java-ReactNative connection is working. But when I call my library function testFunc()
I receive the following error message:
Could not invoke JavaCaller.getLib
null
Native library (com/sun/jna/android-aarch64/libjnidispatch.so) not found in resource path (.)
My project structure is the following:
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"
I load my library within my 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();
}
And call the testFunc()
within my TestCaller.java
public class TetsCaller extends ReactContextBaseJavaModule {
...
@ReactMethod
public void getLib(Callback callback) {
int test = TestLib.INSTANCE.testFunc();
callback.invoke(test);
return;
}
...
}
And my app/build.gradle
file
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"
}
Am I missing something in using JNA? Do I maybe have to exclude
jna inside of my gradle file? I think my dynamic library and my calling seems fine, so the error has to be inside of my gradle file or setting up a wrong path anywhere.
Also from what I have seen within my build.gradle
, the line directory referenced in line from("$reactAndroidProjectDir/src/main/jni/prebuilt/lib")
seems to be empty
Edit:
Also jna has been installed using sudo apt-get install libjna-java
.
Edit2:
I tried to reproduce the path com/sun/jna/android-aarch64/
from the error message by modifying the jna.jar
file (renaming to .zip and back to .jar) and duplicating and renaming the linux-aarch64
-directory to android-aarch64
. Placing the jna.jar into my src/lib dir
and adding it with Android Studio, the line implementation 'net.java.dev.jna:jna:5.12.1'
gets replaced by implementation group: 'net.java.dev.jna', name: 'jna', version: '5.12.1
and the error is still the same. Even though the file should be inside of the directory now.
Edit3:
As pointed out by Daniel Widdis the android-* folders/jar-files are not included in the currently provided jna.jar, therefore I downloaded them, created the corresponding folders inside of my jna.jar and added them (only including the libjnidispatch.so
). Because I use implementation files('libs/jna.5.12.1.jar')
inside of my gradle, they should be picked from the jar. I also created the folders aarch64
and android-aarch64
including the libjnidispatch.so
but the error still keeps coming up. I suppose it is something with my path set up, but I can't tell where.
Also using implementation 'net.java.dev.jna:jna:5.12.1
inside of my gradle and commenting out the implementation files(...)
does not solve this issue.
CodePudding user response:
Using implementation files('libs/jna.5.12.1.jar')
inside app/build.gradle
on android requires to add @aar
to the end of jar
.
implementation files('libs/jna.5.12.1.jar@aar')