Java和JNI - 加载DLL库只能在我的计算机上运行

时间:2011-01-19 15:27:54

标签: java dll load java-native-interface

我正面临一些恼人的问题,让我的java应用程序通过JNI使用外部c ++ dll。这些库位于包内。当我需要将它们加载到虚拟机中时,我将它们复制到临时文件夹。 dll是下一个:

libcurld.dll; libfftw3f-3.dll; libmad.dll; libsamplerate.dll; main.dll;

main.dll是实现java端声明的本机方法的那个。这个dll取决于上面运行正常。我只在visual studio上编译了main.ddl,为xp编译了另一个二进制文件。其他人下载并简单链接。我运行下一个方法来加载java上的库:

public static boolean loadBinaries(){
    String os = System.getProperty("os.name").toLowerCase();
    ArrayList<String> bins = new ArrayList<String>();

    if(os.indexOf("windows 7") >= 0){
        bins.add("/nm/metadata/bin/win/libcurld.dll");
        bins.add("/nm/metadata/bin/win/libfftw3f-3.dll");
        bins.add("/nm/metadata/bin/win/libmad.dll");
        bins.add("/nm/metadata/bin/win/libsamplerate.dll");
        bins.add("/nm/metadata/bin/win/seven/main.dll");
    }
    else if(os.indexOf("windows xp") >= 0){
        bins.add("/nm/metadata/bin/win/libcurld.dll");
        bins.add("/nm/metadata/bin/win/libfftw3f-3.dll");
        bins.add("/nm/metadata/bin/win/libmad.dll");
        bins.add("/nm/metadata/bin/win/libsamplerate.dll");
        bins.add("/nm/metadata/bin/win/xp/main.dll");
    }

    File f = null;
    for(String bin : bins){
        InputStream in = FileManager.class.getResourceAsStream(bin);
        byte[] buffer = new byte[1024];
        int read = -1;
        try {
            String[] temp = bin.split("/");
            f = new File(TEMP_FOLDER + "/" + temp[temp.length-1]);
            File realF = new File(f.getAbsolutePath());
            if(realF.exists())
                f.delete();

            FileOutputStream fos = new FileOutputStream(realF);

            while((read = in.read(buffer)) != -1) {
                fos.write(buffer, 0, read);
            }
            fos.close();
            in.close();

            System.load(f.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    return true;
}

可执行jar总是在我的机器上完美运行,但在其他机器上却没有...我从我的测试中得到了下一个错误:

(xp)
Exception in thread "main" java.lang.UnsatisfiedLinkError: C:\temp\main.dll: Can't find dependent libraries at java.lang.ClassLoader$NativeLibrary.load(Native Method)...

(seven)
C:\temp\main.dll: The application has failed to start because its side-by-side configuration is incorrect...

所有dll都写在temp文件夹中,正如我所说,这在我的计算机中运行良好。我原以为这可能是因为在VS上的调试模式下编译。不幸的是,除非返回更小的二进制文件,否则将其发布并不会改变任何内容。

这可能是什么?视觉工作室是否缺少一些配置细节? 提前谢谢。

1 个答案:

答案 0 :(得分:1)

首先,我会复制所有DLL,然后将它们加载到两个循环中。

其次,从错误消息中看来,还有另一个DLL需要main.dll才能在其他计算机上出现。 可能是C ++运行时库通常没有安装在您需要的版本中,这就是许多游戏或其他应用程序首先安装它们的原因。