Search code examples
javac++macosjava-native-interfacerpath

Is it possible to make the classpath the @rpath in a JNI library?


I have a library that my JNI depends on, I would like it to be loaded relative to the classpath, is this possible?


Solution

  • Relative to the classpath, no, it's not possible - libraries, including .jnilib follow the OS search path defined based on what the JRE assigns, then what the libraries themselves mention.

    When you make the .jnilib, you can to add a linker flag to specify the rpath relative to the 'loader' path for the library, which will allow you to place dependent libraries in a location adjacent to the .jnilib itself, which can accomplish a similar behaviour:

    libjni.jnilib: libjni.o
        $(CC) -o $@ $< -Wl,-rpath,@loader_path/../lib
    

    The important item is the adding of -Wl,-rpath,@loader_path/../lib - which says tell the linker to add @loader_path/../lib to the rpath of the .jnilib.

    The value @loader_path resolves to the location of the .jnilib file at run-time.

    If you want to load dependencies based on the classpath, you'll actually have to find the libraries based on the classpath yourself and explicitly load them into the jre using System.load(), and then they should be pre-resolved by dyld when you load the library that the module depends on.