Search code examples
androidandroid-ndkffmpegjava-native-interfaceandroid-ndk-r7

Remove the instance of native library from app using dlclose(Android NDK)


I have compiled FFmpeg library using NDK and use it to trim videos and get thumbnails from a video in my app, so basically I have ffmpeg.so and video-trimmer.so libraries up and running.

The problem however is strange, the trim or getThumbnail operations are successful but just one time i.e. the first time and the operations fail the second time. However it is successful the third time, I googled it and got two similar posts on SO related to my problem

POST 1:

POST 2:

Interestingly they suggest the same solution and I am unable to solve the issue being a naive in C programming language.

Here is what I have done

void Java_com_example_demo_natives_LibraryLoader_loadTrimmerLibrary(JNIEnv* env, jclass class, jstring libffmpeg_path, jstring inputFile, jstring outFile,
        jstring startTime, jstring length)
{
        const char* path;
        void* handle;
        int *(*Java_com_example_demo_natives_VideoTrimmer_trim)(JNIEnv *, jclass, jstring, jstring, jstring, jstring);

        path = (*env)->GetStringUTFChars(env, libffmpeg_path, 0);

        handle = dlopen(path, RTLD_LAZY);

        Java_com_example_demo_natives_VideoTrimmer_trim = dlsym(handle, "Java_com_example_demo_natives_VideoTrimmer_trim");
        (*Java_com_example_demo_natives_VideoTrimmer_trim)(env, class, inputFile, outFile, startTime, length);

        (*env)->ReleaseStringUTFChars(env, libffmpeg_path, path);

        dlclose(handle);
}

Despite of calling dlclose the library instance still exists in memory, what I am doing wrong here?

I come to know that library instance still exists because when I load the libraries again in some other activity the error message says library already exists in CL.

I want to get rid of the instance of that library from memory, please help...


Solution

  • try moving the position of the 'ReleaseString...'

    it should be after the 'dlopen'

    it should be before the call into the other shared lib...

    (*env)->GetStringUTFChars
    dlopen
    (*env)->ReleaseStringUTFChars
    make the main call
    dlclose