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*作为出参时需要知道对应的字符串长度在获得内容时使用。





附件列表

转载于:https://my.oschina.net/MeiJianMing/blog/1812014

猜你喜欢

转载自blog.csdn.net/weixin_33748818/article/details/92546507
jna
今日推荐