副标题#e#
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”:
单击鼠标右键》新建》类:
#p#副标题#e#
输入包名,类名,勾选“public static void main(String[] args)”,单击“Finish”:
打开项目文件目次:
将要挪用的DLL文件“EhfscliaxDll.dll”复制到此目次下,该DLL的代码请参考:VS2010编写动态链接库DLL及单位测试用例,挪用DLL测试正确性:http://blog.csdn.net/testcs_dn/article/details/27237509
新建“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 要领的<span style="font-family: Arial, Helvetica, sans-serif;">JNative工具</span> 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是获取返回值的指针地点,<span style="font-family: Arial, Helvetica, sans-serif;">getUnicodeMemoryAsString要领从指针地点的内存中读取字符串</span> 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
作者:csdn博客 微wx笑