本文共 2012 字,大约阅读时间需要 6 分钟。
JNA(Java Native Access )提供一组Java工具类用于在运行期动态访问系统本地库(native library:如Window的dll)而不需要编写任何Native/JNI代码。开发人员只要在一个Java接口中描述目标native library的函数与结构,JNA将自动实现Java接口到native function的映射。
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*作为出参时需要知道对应的字符串长度在获得内容时使用。
转载地址:http://otwza.baihongyu.com/