JAVA调用动态链接库DLL的方法有:JNI(Java Native Interface),JInvoke,JNative(Java to native interface),JNI是JAVA自身提供的方法;JInvoke从何而来不得而知,好像还需要注册付费的,64位的JDK、JIR环境下运行不了,在VMware下安装的WindowsXP下同样有问题;JNative是开源的,但相关资料文档也特别的少,好像已经停止更新了。JNative源码地址:http://jnative.cvs.sourceforge.net/viewvc/jnative/,jar包下载地址:http://sourceforge.net/projects/jnative/files/jnative/。
开发环境:myeclipse-10.7-offline-installer-windows
文件》新建》JAVA项目:
输入项目名称,单击“Finish”:
单击鼠标右键》新建》类:
输入包名,类名,勾选“public static void main(String[] args)”,单击“Finish”:
打开项目文件目录:
将要调用的DLL文件“EhfscliaxDll.dll”复制到此目录下,该DLL的代码请参考:VS2010编写动态链接库DLL及单元测试用例,调用DLL测试正确性
新建“lib”文件夹,将JNative.jar复制到此目录下:
配置编译目录:
单击“Add External JARs”添加jar包,下图为已经添加过的:
Helper类代码:
package com.ehfscliax; import org.xvolks.jnative.JNative; import org.xvolks.jnative.Type; import org.xvolks.jnative.exceptions.NativeException; import org.xvolks.jnative.pointers.Pointer; public class Helper { /** * @param args * @throws NativeException */ public static void main(String[] args) throws NativeException { JNative.setLoggingEnabled(true); try { JNative getUrl = new JNative("EhfscliaxDll.dll", "getUrl"); //创建 getUrl 方法的JNative对象 getUrl.setRetVal(Type.STRING); //设置返回值类型为:String getUrl.setParameter(0, "127.0.0.1"); //按顺序设置方法需要的参数值 getUrl.setParameter(1, 10087); getUrl.setParameter(2, 123); getUrl.invoke(); //调用方法 System.out.println(getUrl.getRetVal()); //输出返回值 } catch (IllegalAccessException e) { e.printStackTrace(); } try { JNative getPlayUrl = new JNative("EhfscliaxDll.dll", "getPlayUrl"); getPlayUrl.setRetVal(Type.INT); //此方法在DLL中定义的返回值类型为:const wchar_t*,如果设置返回值类型为:String,则只能获取到返回值的第一个字符 String mgrIp = "127.0.0.1"; Pointer ptr = Pointer.createPointerFromString(mgrIp); getPlayUrl.setParameter(0, ptr); getPlayUrl.setParameter(1, 10087); getPlayUrl.setParameter(2, 123); getPlayUrl.invoke(); //个人理解getRetValAsInt是获取返回值的指针地址,getUnicodeMemoryAsString方法从指针地址的内存中读取字符串 String url = JNative.getUnicodeMemoryAsString(getPlayUrl.getRetValAsInt()); System.out.println(url); } catch (IllegalAccessException e) { e.printStackTrace(); } } }
执行结果:
2014-5-25 22:48:46, [DEBUG] [org.xvolks.jnative.JNative] [loadLibrary]: Successfully loaded library 'EhfscliaxDll.dll', functionName = getUrl: hModule = 268435456 http://中文127.0.0.1:10087 2014-5-25 22:48:46, [DEBUG] [org.xvolks.jnative.pointers.memory.MemoryBlockFactory] [setPreferredMemoryType]: Using org.xvolks.jnative.pointers.memory.HeapMemoryBlock memory reservation strategy http://-�17001:10087 2014-5-25 22:48:46, [DEBUG] [org.xvolks.jnative.JNative] [unLoad]: Unloading native library 'EhfscliaxDll.dll'
getUrl方法的返回值类型为:const char*,结果是正常的,getPlayUrl的返回值类型为:const wchar_t*,虽然通过getUnicodeMemoryAsString读取到了返回值,不是第一个字符,但中文乱码的问题一直没能解决。
本学习项目源码下载:http://download.csdn.net/detail/testcs_dn/7400203