學習JNA,Jnative

thinkyoung發表於2014-10-25

 

首先說下JAVA呼叫DLL,Java呼叫DLL的常用方法大致為幾種,JNI,JNA,Jnative等,但實現與易用性差距還是很大,1.JNI用的人比較多,但相對來說比較麻煩要熟悉c並且要使用javac 及javah命令,步驟繁瑣2.JNA,Jnative相對簡單隻需要用實現介面,使用相對簡單,但無論使用什麼呼叫dll檔案,比較令人頭疼的都是JAVA與C之間型別對應與值對應。下面我將專案中對著JNA及jnative的使用總結下。

1.JNA樣碼

步驟如下:

a,下載JNAjar檔案,拷貝至系統根目錄或者系統system32下

b,程式碼很easy

Java程式碼

package com.cn.app;

import com.sun.jna.Library;
import com.sun.jna.Native;

public class DLLTEST {

// 1.實現PegRoute.dll 檔案介面

public interface PegRoute extends Library {

// 2.PegRoute.dll 中 HCTInitEx方法
public int HCTInitEx(int Version, String pStrCurrentDirectory);
}

public static void main(String[] args) {
//3.載入DLL檔案,執行dll方法
PegRoute epen = (PegRoute) Native.loadLibrary(“PegRoute”,
PegRoute.class);
if (epen != null) {
System.out.println(“DLL載入成功!”);
int success = epen.HCTInitEx(0,””);
System.out.println(“1.裝置初始化資訊!” + success);
}
}
}

 

 

2.Jnative樣碼

1.下載jnative。jar 及JNativeCpp.dll
2.將使用的dll檔案及JNativeCpp.dll拷貝至系統system32下
3.樣碼

Java程式碼

import org.xvolks.jnative.JNative;
import org.xvolks.jnative.exceptions.NativeException;
import org.xvolks.jnative.Type;
import org.xvolks.jnative.misc.basicStructures.LONG;

public class JNativeT {

static JNative PegRoute = null;

public String init() throws NativeException, IllegalAccessException {
try {
if (PegRoute == null) {
// 1. 利用org.xvolks.jnative.JNative來載入DLL:引數1.PegRoute為類名
// 2.HCTInitEx方法名
PegRoute = new JNative(“PegRoute”, “HCTInitEx”);

// 2.設定要呼叫方法中的引數:0 表示第一個以此類推
LONG versionLong = new LONG(10);
versionLong.setValue(0);

PegRoute.setParameter(0, Type.LONG, versionLong.toString());
PegRoute.setParameter(1, Type.STRING, “”);

// 3.設定返回引數的型別
PegRoute.setRetVal(Type.INT);
// 4.執行方法
PegRoute.invoke();// 呼叫方法
}
System.out.println(“呼叫的DLL檔名為:” + PegRoute.getDLLName());
System.out.println(“呼叫的方法名為:” + PegRoute.getFunctionName());
// 5.返回值
return PegRoute.getRetVal();
} finally {
if (PegRoute != null) {
// 6.釋放系統資源
PegRoute.dispose();
}
}
}

public static void main(String[] args) throws NativeException,
IllegalAccessException {

String mm = new JNativeT().init();
System.out.println(mm);
}
}

 


相關文章