由于种种原因,项目需要调用dll文件中的接口,于是各种百度。。。,发现有3种方法,我只弄成功了一种,在这里把我的流程记录下来,方便以后查找。
这里用的是通过JNative的方式,这种方式最简单,不过需要引入一个JNative.jar,我测试是用的web的方法,直接通过main函数运行没有成功,可能和库的加载有关系,这里我就直接粘贴我的代码了(JNative.jar下载):
/**这个类负责调用dll中接口*/
package com;
import org.xvolks.jnative.JNative;
import org.xvolks.jnative.Type;
import org.xvolks.jnative.exceptions.NativeException;
public class Test {
static JNative myjnative = null;
public String getOrderCode(String orderCode) throws NativeException,IllegalAccessException{
try {
if (myjnative == null) {
myjnative = new JNative("CRCDll.dll", "GetCRC8");
myjnative.setRetVal(Type.STRING);
}
myjnative.setParameter(0, orderCode);
myjnative.invoke();
return myjnative.getRetVal();
} finally {
if (myjnative != null) {
myjnative.dispose();
}
}
}
}
/**这个是servlet的代码*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(""-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("");
out.println("
A Servlet");out.println("
");out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
try {
//这里获取结果
Test test = new Test();
String ordersCode = test.getOrderCode(request.getParameter("ordersCode"));
System.out.println(ordersCode);
out.println("ordersCode:"+ordersCode);
} catch (NativeException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
out.println(" ");
out.println("");
out.flush();
out.close();
}