天天看點

JNA簡介JNA

JNA

JNA(Java Native Access )提供一組Java工具類用于在運作期動态通路系統本地庫(native library:如Window的dll)而不需要編寫任何Native/JNI代碼。開發人員隻要在一個Java接口中描述目标native library的函數與結構,JNA将自動實作Java接口到native function的映射。
  • 優點:JNA可以讓你像調用一般java方法一樣直接調用本地方法。就和直接執行本地方法差不多,而且調用本地方法還不用額外的其他處理或者配置什麼的,也不需要多餘的引用或者編碼,使用很友善。
  • 缺點:JNA是建立在JNI的基礎之上的,是以效率會比JNI低。

關鍵代碼

import com.sun.jna.Library;
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.IntByReference;
public class LYTest {
    public interface CLibrary extends Library {
        CLibrary INSTANCE = (CLibrary)Native.loadLibrary("ly_icparse",CLibrary.class);
        int Parse(String databuf,IntByReference ickh,IntByReference quantity,IntByReference fc,Pointer cid);
        int Build(int ickh, int quantity, int fc, String cid, Pointer databuf);
    }
    public static void main(String[] args) throws Exception {
        //用于接收輸出的char*
        Pointer databuf = new Memory(512);  
        CLibrary.INSTANCE.Build(20133058, 11, 3, "201013000285", databuf);
        byte[] byteArray = databuf.getByteArray(0, 512);
        String data = new String(byteArray,"UTF-8");
        System.out.println("data:"+data);
        //建構讀卡資料
        String databufstr = "A2131091FFFF8115FFFF201013000285FFFFFFFFFFD27600000400FFFFFFFFFF"+data.substring(64,512);

        IntByReference ickh = new IntByReference();
        IntByReference quantity = new IntByReference();
        IntByReference fc = new IntByReference();
        Pointer cid = new Memory(12);
        int result = CLibrary.INSTANCE.Parse(databufstr, ickh, quantity, fc, cid);
        String cidstr =  new String(cid.getByteArray(0, 12),"UTF-8");
        System.out.println("ickh:"+ickh.getValue());
        System.out.println("quantity:"+quantity.getValue());
        System.out.println("fc:"+fc.getValue());
        System.out.println("cid:"+cidstr);
        System.out.println("result:"+result);
    }
}           

說明

常用的c于java參數對應關系

c參數 java參數
int* IntByReference 出參,入參直接用int
char* Pointer/Memory 出參,入參直接用String
char*作為出參時需要知道對應的字元串長度在獲得内容時使用。
來自為知筆記(Wiz)