简体   繁体   中英

How to call a function defined in shared library (cross-compiled on linux) in Android App?

I am developing an android app where I have to use a shared library (cross-compiled on linux system using NDK toolchain).

Below are the steps I followed:

  1. I am using the ' hello-libs ndk sample '.
  2. The shared library name is libsum.so , where I have two function definitions:
int sum(int a, int b);
int sub(int a, int b);
  1. I have copied libsum.so file to the android app under path //hello-libs/app/libs/arm64-v8a and called sum(10, 20) in //hello-libs/app/src/main/cpp/hello-libs.cpp file.
  2. Updated the CMakeLists.txt file to add shared library while compiling. Updated CMakeLists.txt file below:
...
...
# configure import libs
set(distribution_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../../../distribution)
...
...
add_library(lib_sum SHARED IMPORTED)
set_target_properties(lib_sum PROPERTIES IMPORTED_LOCATION
    ${distribution_DIR}/sum/lib/${ANDROID_ABI}/libsum.so)

# build application's shared lib
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++11")

add_library(hello-libs SHARED
            hello-libs.cpp)

target_include_directories(hello-libs PRIVATE
                           ${distribution_DIR}/gmath/include
                           ${distribution_DIR}/gperf/include
                           ${distribution_DIR}/sum/include)

target_link_libraries(hello-libs
                      android
                      lib_gmath
                      lib_gperf
                      lib_sum
                      log)

main.h

#include <stdio.h>

int sum(int a, int b); 
int sub(int a, int b);

But I am getting the below error:

ld: error: undefined symbol: sum(int, int)

Can somebody please help me?

如果尚未完成,您可能希望使用 JNIEXPORT 宏向函数添加可见性标志,该宏扩展为属性((visibility("default"))):

extern "C" { JNIEXPORT jint JNICALL Java_com_example_MyActivity_sum(JNIEnv * env, jobject thisObject, jint a, jint b) { return a + b; } } // extern C

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