Search code examples
androidcandroid-ndkjava-native-interface

Call native library method in independent native library


I am trying to implement the solution stated in this stackoverflow post.

As the solution suggests, I created a independent native library. This how I have implemented that library thus far.

#include "zoom_Main_VideoPlayer.h"
#include <dlfcn.h>

void *handle;
typedef int (*func)(int); // define function prototype
func myFunctionName; // some name for the function

JNIEXPORT void JNICALL Java_zoom_render_RenderView_naClose(JNIEnv *pEnv, jobject pObj) {

    handle = dlopen("path to nativelibrary1.so", RTLD_LAZY);
    myFunctionName = (func)dlsym(handle, "Close");
    myFunctionName(1); // passing parameters if needed in the call
    dlclose(handle);
    return;
}

According to the solution, build another independent native library (utility library) to load and unload the other libraries. Thus, I am trying to load and unload nativelibrary1 in this independent library. For example, the native method in this other native library is such

// native method in nativelibrary1
JNIEXPORT void JNICALL Java_zoom_render_RenderView_naClose(JNIEnv *pEnv, jobject pObj) {

    if (!is) {
        do_exit(is);
    }
    else {
        do_exit(NULL);
    }

    LOGI(0, "Clean-up done");
}

I am not sure how I am supposed to modify nativelibrary1 since they aren't native methods called directly in the java code anymore (the nativelibrary1 lib is not loaded directly in the static block of the java code).

Also am I supposed to change typedef int (*func)(int); // define function prototype to fit the type of the method in nativelibrary1?


Solution

  • Its kind of unclear what you want the function to do, but If I understand, you want your Java-callable library to be like the following (assuming "C" not C++)

    #include "zoom_Main_VideoPlayer.h"
    #include <dlfcn.h>
    void *handle;
    typedef void (*func)(); // define function prototype
    func myFunctionName; // some name for the function
    JNIEXPORT void JNICALL Java_zoom_render_RenderView_naClose(JNIEnv *pEnv, jobject pObj) {
    
        handle = dlopen("path to nativelibrary1.so", RTLD_LAZY);
        myFunctionName = (func)dlsym(handle, "Close");
        myFunctionName(); // passing parameters if needed in the call
        dlclose(handle);
        return;
    }
    

    And your other library will be:

    // native method in nativelibrary1
    void Close() {
        if (!is) {
            do_exit(is);
        }
        else {
            do_exit(NULL);
        }
        LOGI(0, "Clean-up done");
    }
    

    Because your Close() does not have any arguments. You may also make your Java method static so that the spurious pObj isn't added to the native method signature.

    If you described what the methods should do, I could make a better suggestion.