“放弃Jni”愉快的奔向JNA
2017-12-13 14:01 阅读(251)

JNA的使用

使用背景

对比

如上图所示Jna省去了令Java程序员头疼的Jni中间键共享库的封装。官方言简意赅的描述:JNA provides Java programs easy access to native shared libraries without writing anything but Java code - no JNI or native code is required.

3.png

编译得到wer.so里面有add方法。

5.png

6.png

在编写jni中间键的时候还要注意头文件的引用,方法的全路径,Android.mk的配置,稍有不慎在调用的时候就会引起喜闻乐见的崩溃。

Jna的调用

仅仅这么一步就搞定了,激动不!!!

JNA简介

JNA的使用

c代码实现

int getName(char *name,char * s) {
    if(name==NULL||s==NULL){
        return -1;
    }
    int result=strcmp(name, "大包子");
    char  dabaozi[40] ="大包子最帅!";
    char other [40] = "其他人一般帅。。。";
        if (result == 0) {

        memcpy(s, dabaozi, strlen(dabaozi));
    }
    else {
        memcpy(s, other, strlen(other));
    }

    return 0;
}

java代码调用

String s = et_name.getText().toString();
 byte [] bytename=new byte[50];
ByteBuffer call=ByteBuffer.wrap(bytename);
ByteBuffer name=ByteBuffer.wrap(new String(s).getBytes());
int re = JnaTools.INSTANCE.getName(name, call);
tv_result.setText(new String(call.array()));

c代码实现

int getAge(int *age){    
    *age=18;    
    return 0;
}

java代码

String s = et_name.getText().toString();
 byte [] bytename=new byte[50];
ByteBuffer call=ByteBuffer.wrap(bytename);
ByteBuffer name=ByteBuffer.wrap(new String(s).getBytes());
int re = JnaTools.INSTANCE.getName(name, call);
tv_result.setText(new String(call.array()));