I am developing a Java application that should be release as a jar. This program depends on C++ external libraries called by JNI. To load them, I use the me
I don't believe you can load the DLL directly from the JAR. You have to take the intermediary step of copying the DLL out of the JAR. The following code should do it:
public static void loadJarDll(String name) throws IOException {
InputStream in = MyClass.class.getResourceAsStream(name);
byte[] buffer = new byte[1024];
int read = -1;
File temp = File.createTempFile(name, "");
FileOutputStream fos = new FileOutputStream(temp);
while((read = in.read(buffer)) != -1) {
fos.write(buffer, 0, read);
}
fos.close();
in.close();
System.load(temp.getAbsolutePath());
}
You need to prime the classloader with the location of the DLL -- but it can be loaded without extracting it from the jar. Something simple before the load call is executed is sufficient. In your main class add:
static {
System.loadLibrary("resource/path/to/foo"); // no .dll or .so extension!
}
Notably, I experienced basically the same issue with JNA and OSGi's handling of how the DLLs are loaded.
This JarClassLoader aiming to solve the same problem:
http://www.jdotsoft.com/JarClassLoader.php
Basically this should work. As this is the way JNA does it, simply download it and study the code. YOu even have some hints to make this platform independent...
EDIT
JNA brings its native code along in the jar, unpacks the correct binary at runtime und loads it. This may be a good pattern to follow (if i got your question correct).