Search code examples
androidgccandroid-ndkjava-native-interfaceshared-libraries

Android JNI Using Pre built .so file in C Code


I am trying my hand at Android JNI. So far I have just written the basic Hello World Android JNI App. Now I was thinking if it would be possible to build a .so file seperately. Then use that library in my JNI Layer C Code.

So basically I want to build a libsample.so using command line gcc in windows. Then use this .so file in the JNI I write for my android app. So far from my understanding I should be able to do this by editing the Android.mk file.

But what would those edits be ?

EDIT: Source code attached.

jnitest.cpp -

#include <jni.h>
#include "specialPrint.h"

extern "C" jstring Java_com_example_hwjni_MainActivity_helloFromJni(JNIEnv *env, jobject thiz) {
    return env->NewStringUTF(SpecialPrint("This is external .so talking."));
}

specialPrint.h -

#include <stdio.h>
#ifdef __cplusplus
extern "C" {
#endif
char* SpecialPrint(char* s);
#ifdef __cplusplus
}
#endif

specialPrint.c -

#include <stdio.h>
#include "specialPrint.h"

char* SpecialPrint(char* s) {
    return s;
}

Android.mk

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
LOCAL_MODULE := MyPrebuiltLib
LOCAL_SRC_FILES = specialPrint.c
include $(BUILD_SHARED_LIBRARY)

include $(CLEAR_VARS)
LOCAL_MODULE    := jnitest
LOCAL_SRC_FILES := jnitest.cpp
LOCAL_SHARED_LIBRARIES := MyPrebuiltLib
include $(BUILD_SHARED_LIBRARY)

P.S. - Although right now I am trying to do this with the source. But eventually I really need to do this stuff without the source of specialPrint. If you could help me achive that then it would be great!


Solution

  • Step 1: declare a prebuilt library as module Step 2: refer the prebuilt module as local shared library

    for example

    include $(CLEAR_VARS)
    LOCAL_MODULE := MyPrebuiltLib
    LOCAL_SRC_FILES = path/to/libSuper.so
    include $(PREBUILT_SHARED_LIBRARY)
    
    include $(CLEAR_VARS)
    LOCAL_MODULE := DroidJNILib
    LOCAL_SRC_FILES := AwsomeCode.cpp
    LOCAL_SHARED_LIBRARIES := MyPrebuiltLib
    include $(BUILD_SHARED_LIBRARY)
    

    If you have the source

    include $(CLEAR_VARS)
    LOCAL_MODULE := MyPrebuiltLib
    LOCAL_SRC_FILES =mysource.cpp
    include $(BUILD_SHARED_LIBRARY)
    
    include $(CLEAR_VARS)
    LOCAL_MODULE := DroidJNILib
    LOCAL_SRC_FILES := AwsomeCode.cpp
    LOCAL_SHARED_LIBRARIES := MyPrebuiltLib
    include $(BUILD_SHARED_LIBRARY)