I have been struggling lately with loading dll's which I need to make an application work. Setting the library path -Djava.library.path=some/path/to/dll was not really an option as our application is distributed via Webstart where all the resources need to be needly packaged in a couple of jars.
I decided to take a hard look at the System.load() command where you pass a string to the dll location. With a little bit of help from class loaders, this can work.
I stored a DLL in the package run.dll with the name of test.dll
The following code snippet will find the location of the resource:
private static final String SUFFIX = ".dll";
public static String loadDLL(String name) throws Exception {
//result variable
String result = null;
//package name can be loaded with '/' or '.'
if (name.startsWith( "/" ) ) { name = name.substring(1); }
//add the .dll to the end of the name
if (!name.endsWith(SUFFIX) { name = name.concat(SUFFIX); }
//replace '.' with '/'
name = name.replace('.', '/');
//use the default class loader
ClassLoader loader = ClassLoader.getSystemClassLoader();
//get the resource
java.net.URL = loader.getResource(name);
//the URl file format is /drive:/path/to/dll/dll.dll
//therefore, strip the first '/' and replace the remaining
//'/' with whatever file separator is applicable for
//your OS
result = url.getFile().substring(1).replace("/", File.separator);
//path to resource
return result;
}
This can now be launched as:
public static void main (String args[]) {
try {
//now we can load the dll using system.load();
system.load ( loadDLL("some.pkg.test.dll") ) ;
} catch (Exception e) {
e.printStackTrace();
}
}
Friday, June 19, 2009
Subscribe to:
Posts (Atom)