Search code examples
javaandroid-ndkjava-native-interfacejna

System.LoadLibrary during runtime or controlled by user


Is it possible to load a native library in response to user interaction by means of UI event? Eg, button click etc calls System.LoadLibrary(file_chosen_dynamically) or conditional loading (in the case of a CLI) Perhaps a good example would be like a file picker to select the dll/so file

From what I understand, this is done when the class instantiates. Can I just call System.LoadLibrary as desired or do I need to use class loader?

Is this the same with all platforms (Android/Desktop)


Solution

  • Is it possible to load a native library in response to user interaction by means of UI event?

    Technically, yes.

    From what I understand, this is done when the class instantiates.

    That is the normal way to do it. You normally put the loadLibrary call into a static block so that it is executed when the class initializes.

    Can I just call System.LoadLibrary as desired or do I need to use class loader?

    1. Yes (technically)

    2. No. A class loader isn't / doesn't need to be involved.

    I say "technically", because there is a practical problem with calling loadLibrary somewhere other than in a static initializer block.

    The primary effect of calling loadLibrary is that native methods declarations will be "bound" to the corresponding native code implementations. If you call loadLibrary at class initialization time, then you are pretty much guaranteed that the binding has happened before the native methods can be called. But, if you call loadLibrary at another time (after class initialization), there is a risk that some code will call a native method before it has been bound to its implementation. That will trigger an Error ... and it is pretty much game over.

    So ... rather than interactively selecting a DLL, I think you are better off having a one-to-one relationship between DLLs and Java classes, and interactively selecting a class to be loaded using Class.forName.


    Is this the same with all platforms (Android/Desktop)

    I believe so ...