简体   繁体   中英

Call a SO function in C++ class in Android NDK

How to call a function from prebuild .so (C class) file into C++ class in new project. For example i have a project-1 which create a prebuild .so file. Now in this project i have a C++ file named as "androidNdk". In this class i have only one function that return a integer value.

int myFunction()
{
    int number = 10;
    return number;
}

Header file of this class

int myFunction();

I create a new project and load this .so file and call a myfunction() in C++ class. like this This is new class named as "newAndroidNdk".

void newFunction()
{
    int str = myFunction();

    printf("%s", str);  
}

The problem is when i compile this project using ndk-build command it will give me this error "undefined reference to myfunction".

This is Android.mk in jni -> lib folder

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

LOCAL_MODULE := libndkfunction-prebuilt
LOCAL_SRC_FILES := libndkfunction.so
LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/include
include $(PREBUILT_SHARED_LIBRARY)

This is new project Android.mk file

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)

# Here we give our module name and source file(s)
LOCAL_MODULE    := ndkfun
LOCAL_SRC_FILES := ndkfun.c

LOCAL_SHARED_LIBRARIES := libndkfunction-prebuilt        
 LOCAL_EXPORT_C_INCLUDES := $(LOCAL_PATH)/jni/include                
include $(BUILD_SHARED_LIBRARY)

help me to solve this problem

You cannot call native code directly from java, you need use JNI. You can read more about it on official java site or android developers site. You should use javah to generate native function wrapper for java code, it's more conveniently. Or manually declare static function and write wrapper for its C/C++ declaration Little tutorial

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