通过jnative调用dll 。
下截JNative组件
jnative.sourceforge.net/ 到这里下载JNative开源项目,我下载的是1.3.2
解压JNative.zip
获得三个文件,分别是:JNativeCpp.dll,libJNativeCpp.so,JNative.jar 。
JNativeCpp.dll Windows下用的,拷贝到windows / system32目录下;
libJNativeCpp.so Linux下的,拷贝到系统目录下;
JNative.jar 这是一个扩展包,导入工程LIB中或将其拷贝到jdk\jre\lib\ext 下,系统会自动加载。
在源代码运行的过程中,Exception in thread "main" java.lang.IllegalStateException: JNative library not loaded, sorry !
如果报这个异常把TestJndi.dll和JNativeCpp.dll放到拷贝到java.library.path下,比如jdk的bin目录下。
在TestJndi.dll的名字叫sayHello,如果在test1方法中用这个名字,会报找不到sayHello方法,用dll查看器,下载地址:
http://www.onlinedown.net/softdown/17471_2.htm,查看正确的函数名字,为_Java_navtiveinterface_JndiTest_sayHello@8。
TestJndi.dll参考http://blog.youkuaiyun.com/qqqwwwqw/article/details/16810715
源代码:
package navtiveinterface;
import org.xvolks.jnative.JNative;
import org.xvolks.jnative.Type;
import org.xvolks.jnative.exceptions.NativeException;
public class JNativeTest {
private static void test1() throws Exception{
JNative n = null;
try{
n = new JNative("TestJndi.dll", "_Java_navtiveinterface_JndiTest_sayHello@8");
n.setRetVal(Type.VOID);
n.setParameter(0,Type.STRING," xuhong ");
n.invoke();
}finally{
if(n != null)
try {
n.dispose();
} catch (NativeException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
private static void test2() throws Exception{
JNative n = null;
try{
n = new JNative("user32.dll", "MessageBoxA");
n.setParameter(0,Type.INT,"0");
n.setParameter(1,Type.STRING,"jnative create window");
n.setParameter(2,Type.STRING,"think jnative");
n.setParameter(3,Type.INT,"0");
n.invoke();
}finally{
if(n != null)
try {
n.dispose();
} catch (NativeException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception{
test1();
test2();
}
}