Java - loading native libraries for 32 and 64 bit OS

Recently I had I problem with loading dll libraries for my java web start application. 32 bit library didn’t load on 64 bit OS and, of cause, vice verse.

Java has “arch” option for resources, and you can try to use it…

1
2
3
4
5
6
7
8
9
<resources os="Windows" arch="x86">
<nativelib href="native-x86.jar" />
</resources>
<resources os="Windows" arch="x86_64">
<nativelib href="native-x86_64.jar" />
</resources>
<resources os="Windows" arch="amd64">
<nativelib href="native-amd64.jar" />
</resources>

But funny problem is that 64x Windows user sometimes installs 32 bit java machine. And it won’t load your 64 bit dll. Also, solution with

1
System.getProperty("os.arch");

doesn’t help you for same reason - it shows OS version, not version of java machine.

You can try a bit cheating with

1
2
3
4
5
6
7
8
9
10
is64bit = (System.getenv("ProgramFiles(x86)") != null);
</pre>
but it really looks ugly and you will only be able to load library after running the main jar module.

So I decided to make a really fun solution:
```xml
<resources os="Windows">
<nativelib href="native.64.dll.jar"/>
<nativelib href="native.32.dll.jar"/>
</resources>

and

1
2
3
4
5
6
7
8
9
10
11
12
13
try {
System.loadLibrary("native.64");
} catch (Throwable t) {
System.out.println("Failed to load library 64x");
t.printStackTrace(System.out);
}

try {
System.loadLibrary("native.32");
} catch (Throwable t) {
System.out.println("Failed to load library 32x");
t.printStackTrace(System.out);
}

One of the libraries loads anyway : )

Of cause, this solution is not cool and won’be acceptable if you have really large library files… But in most cases it’s fine.