Java:d​​ll之间的切换取决于系统架构(32/64)

我有一个Java程序使用一些dll。 由于这些嵌入式dll必须为特定的系统架构(32或64位)构建,我想制作一个方法/允许我的程序在32/64位版本的dll之间切换(或者如果程序运行则禁用库加载)在64位系统上)

我希望有一个解决方案不同于制作两个版本的程序

提前谢谢,Damien

使用系统属性:

if ("x86".equals(System.getProperty("os.arch"))) { // 32 bit } else if ("x64".equals(System.getProperty("os.arch"))) { // 64 bit } 

您可以使用系统属性sun.arch.data.model

 String dataModel = System.getProperty("sun.arch.data.model"); if("32").equals(dataModel){ // load 32-bit DLL }else if("64").equals(dataModel){ // load 64-bit DLL }else{ // error handling } 

小心:此属性仅在Sun VM上定义!

参考:

  • Java HotSpot FAQ>编写Java代码时,如何区分32位和64位操作?

一种蛮力的方式就是奔跑

 boolean found = false; for(String library: libraries) try { System.loadLibrary(library); found = true; break; } catch(UnsatisfiedLinkError ignored) { } if(!found) throw new UnsatifiedLinkError("Could not load any of " + libraries); 

如果您正在使用OSGi和JNI,则可以通过Bundle-NativeCode指定适用于清单中不同平台和体系结构的DLL。

例如:

  Bundle-NativeCode: libX.jnilib; osname=macOSX, X.dll;osname=win32;processor=x86 

定义一个表示DLL API的java接口,并提供两个实现,一个调用32位DLL,另一个调用64位版本:

 public interface MyDll { public void myOperation(); } public class My32BitDll implements MyDll { public void myOperation() { // calls 32 bit DLL } } public class My64BitDll implements MyDll { public void myOperation() { // calls 64 bit DLL } } public class Main { public static void main(String[] args) { MyDll myDll = null; if ("32".equals(args[0])) { myDll = new My32BitDll(); } else if ("64".equals(args[0])) { myDll = new My64BitDll(); } else { throw new IllegalArgumentException("Bad DLL version"); } myDll.myOperation(); } }