java中jni调用不需要配置dll的处理代码

来源:互联网 发布:奇迹归来神器进阶数据 编辑:程序博客网 时间:2024/05/16 18:42

我们在使用jni调用时,常规情况是需要配置dll 。有时因环境等其他因素,总是出现找不到dll 的情况。

因此我研究了一下不用配置dll  的代码处理方法(其实现原理不少开源组件也类似)。

说明:该方式本人已调通window32/window64 /linux32/linux64操作系统下的环境可以正常调用。对于c++封装需要适应不同平台下用java或c#的调用,大家如果有什么问题可以评论和我交流。

public class Test {static{ String os = System.getProperty("os.name");String arch = System.getProperty("sun.arch.data.model");//JDK:sun.arch.data.model  System:os.archString libName = "TestDLL";if(arch != null && arch.indexOf("64") > -1){if(os != null && os.toUpperCase().indexOf("WIN") > -1){libName = "TestDLL.dll";}else{libName = "TestDLL_X64.so";}}else{if(os != null && os.toUpperCase().indexOf("WIN") > -1){libName = "TestDLL_X64.dll";}else{libName = "TestDLL_X64.so";}}String path = loadLibFile(libName);System.load(path);}public static String loadLibFile(String name){String targetFile = System.getProperty("java.io.tmpdir")+ name;String libName = name; try {InputStream is = ClassLoader.getSystemResourceAsStream(libName);OutputStream fos = new FileOutputStream(targetFile);byte[] buffer = new byte[1024];int len = -1;while ( (len = is.read(buffer) )> -1) {fos.write(buffer,0,len);}is.close();fos.close();} catch (Exception e) {e.printStackTrace();}return targetFile;}}


0 0
原创粉丝点击