JNA 参数映射关系

1 使用

点击跳转 JNA地址
jna.jar 下载

  1. 下载jna.jar 导入,并导入so库
  2. 定义JNA 接口,统一将so库function 封装到接口中
public interface IJnaLibrary extends Library {
    public static final String JNA_LIBRARY_NAME = "so file name";
    public static final NativeLibrary JNA_NATIVE_LIB = NativeLibrary.getInstance(IJnaLibrary.JNA_LIBRARY_NAME);
    public static final IJnaLibrary INSTANCE = Native.loadLibrary(IJnaLibrary.JNA_LIBRARY_NAME, IJnaLibrary.class);
	    /**
     *
     * @param hDevHandle  设备句柄
     * @param psDevStatus 自定义结构体 out
     * @param psStatus    错误码及错误信息 out
     * @return
     */
    int GetDevStatus(HANDLE hDevHandle, DevStatus psDevStatus, ErrorDesc psStatus);
}
  1. 调用,在外层包装类中调用,
    public int getDevStatus(HANDLE hDevHandle, DevStatus psDevStatus, ErrorDesc psStatus) {
        return IJnaLibrary.INSTANCE.GetDevStatus(hDevHandle, psDevStatus, psStatus);
    }

2 结构体映射

将 Java Bean与 C 结构体建立映射关系
char --> byte
char * --> String

@Structure.FieldOrder({"cEntryHasNotes", "cEscrowHasNotes", "cExitHasNotes"})
public class DevStatus {
    private byte cEntryHasNotes;  
    private byte cEscrowHasNotes;   
    private byte cExitHasNotes;   
    
    public static class ByReference extends DevStatus implements Structure.ByReference {}
    public static class ByValue extends DevStatus implements Structure.ByValue {}

}

3 回传参数传递

  1. int&
// short、Long float、double 以此论推
IntByReference iLength = new IntByReference(10);
int value = iLength.getValue();
  1. char *
// 将String -->byete[] 数组 再转成 Pointer 指针下发
 public int getDebugInfo(HANDLE hDevHandle, int iDebugInfo, String psPath, byte[] acFileName, ErrorDesc psStatus) {
        Pointer pPara = new Memory(acFileName.length + 1);

        for (int i = 0; i < acFileName.length; i++) {
            pPara.setByte(i, acFileName[i]);
        }
        // 调用接口,下发参数
        int status = IJnaLibrary.INSTANCE.GetDebugInfo(hDevHandle, iDebugInfo, psPath, pPara, psStatus);
        // 获取pPara 返回的 byte[]
        byte[] tempByteArray = pPara.getByteArray(0, acFileName.length + 1);
        // copy 到传入原数组中,返回后将原数组转成String
        System.arraycopy(tempByteArray, 0, acFileName, 0, acFileName.length);
        long peer = Pointer.nativeValue(pPara);
        Native.free(peer);// 手动释放内存
        Pointer.nativeValue(pPara, 0);// 避免 Memory 对象被GC时 重复执行Native.free();
        return status;
    }

最后在方法调用处 将acFileName转成String 获取底层返回的字符串

如果传递json 是否可以用JSON

  1. Bool 布尔 待验证
// 通过Pointer  设置 0、1;代替 true或 false
Pointer bStopFlag = new Memory(0);
int anInt = bStopFlag.getInt(0);

你可能感兴趣的:(Android,开发随笔)