简体   繁体   中英

Problem getting native code to work in a module in Android Studio

I'm trying to build an Android library that has a combo of native code and Java code calling the C++ code. The C++ is stictly limited to the library. I managed to get a project compiling, but when I launch the unit testing, I get an exception that it cannot find the library.
I checked and the code does generate the.so files, but they just can't be found.

So, I created an empty activity project and created in it a module for an Android library. In it, I placed my code in the src/main/cpp directory, along with a CMakeLists.txt file:
libnative.cpp :

#include "libnativeJNI.h"

#ifdef __cplusplus
extern "C" {
#endif

JNIEXPORT jint JNICALL GEN_FUNCNAME(TestFunction)(JNIEnv *jenv, jobject jobj)
{
    return 0;
}

#ifdef __cplusplus
}
#endif

libnative.h :

#ifndef NDKTROUBLESHOOT_LIBNATIVEJNI_H
#define NDKTROUBLESHOOT_LIBNATIVEJNI_H

#include "jni.h"
#define GEN_FUNCNAME(FUNCNAME) Java_com_java_libnative_libnative_##FUNCNAME

#endif //NDKTROUBLESHOOT_LIBNATIVEJNI_H

CMakeLists.txt :

cmake_minimum_required(VERSION 3.10.2)
project("LibNative")
add_library(LibNative SHARED libnativeJNI.cpp)
find_library(log-lib log)
target_link_libraries(LibNative ${log-lib})

I also updated gradle inside the module to compile the native code by adding the following lines in the android section:

    externalNativeBuild {
        cmake {
            path file('src/main/cpp/CMakeLists.txt')
        }
    }

The native code is linked to the Java class in src/main/java/com/java/libnative/ :
libnative.java :

package com.java.libnative;

public class libnative {
    static
    {
        System.loadLibrary("LibNative");
    }

    private native int TestFunction();

    public libnative()
    {
        TestFunction();
    }
}

I can also see the native code being compiled in a library as libnative/build/intermediates/cmake/debug/obj/{Architecture}/libLibNative.so .

Now, the IDE recognizes the native functions, but I created a unit test in the module to test if it actually works:

package com.java.libnative;
import org.junit.Test;

public class UnitTest {
    @Test
    public void library_canLoad()
    {
        new libnative();
    }
}

However, doing so triggers an exception on run:

java.lang.UnsatisfiedLinkError: no libnative in java.library.path

What am I missing to make this work?

Turns out, as mentioned by Michael , that the test environment doesn't support the loading of a native library. I tested the same code by sending it to a phone bundled in an app and it worked fine.
Therefore in this case, the unit testing cannot be used to test the library unfortunately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM