• Android中JNI 的一些常用Method说明


    Android JNI和NDK关系 
    1、什么JNI
    Java Native Interface (JNI)标准是java平台的一部分,它允许Java代码和其他语言写的代码进行交互。JNI 是本地编程接口,它使得在 Java 虚拟机 (VM) 内部运行的 Java 代码能够与用其它编程语言(如 C、C++ 和汇编语言)编写的应用程序和库进行交互操作。
    上面过程分为2个部分:
    第一、用C语言生成一个库文件。
    第二、在java中调用这个库文件的函数。
    2、NDK
    NDK全称:Native Development Kit。
    NDK是一系列工具的集合。
    * NDK提供了一系列的工具,帮助开发者快速开发C(或C++)的动态库,并能自动将so和java应用一起打包成apk。这些工具对开发者的帮助是巨大的。
    * NDK集成了交叉编译器,并提供了相应的mk文件隔离CPU、平台、ABI等差异,开发人员只需要简单修改mk文件(指出“哪些文件需要编译”、“编译特性要求”等),就可以创建出so。
    * NDK可以自动地将so和Java应用一起打包,极大地减轻了开发人员的打包工作。
    个人理解,NDK就是能够方便快捷开发.so文件的工具。
    JNI的过程比较复杂,生成.so需要大量操作,而NDK就是简化了这个过程。


    registerNativeMethods


    传统java  Jni方式:1.编写带有native方法的Java类;--->2.使用javah命令生成.h头文件;--->3.编写代码实现头文件中的方法,这样的“官方” 流程,但也许有人无法忍受那“丑陋”的方法名称,

    通用方 式:RegisterNatives方法能帮助你把c/c++中的方法隐射到Java中的native方法,而无需遵循特定的方法命名格式。应用层级的 Java类别透过VM而呼叫到本地函数。一般是仰赖VM去寻找*.so里的本地函数。如果需要连续呼叫很多次,每次都需要寻找一遍,会多花许多时间。此 时,组件开发者可以自行将本地函数向VM进行登记,VM调registerNativeMethods()函数的用途有二:  (1)更有效率去找到函 数。  (2)可在执行期间进行抽换。由于gMethods[]是一个<名称,函数指针>对照表,在程序执行时,可多次呼叫 registerNativeMethods()函数来更换本地函数之指针,而达到弹性抽换本地函数之目的。

     

    1. cpp文件中  
    2.   
    3. static JNINativeMethod methods[] = {  
    4.     {"native_setText","([BJI)I",(void*)native_setText },  
    5.     {"native_clearText","(I)I",(void*)native_clearText },  
    6.     {"native_create","(I)I",(void*)native_create },  
    7.     {"native_start","()I",(void*)native_start },  
    8.     {"native_next","()I",(void*)native_next },  
    9.     {"native_flush","()I",(void*)native_flush },  
    10.     {"native_stop","()I",(void*)native_stop },  
    11.     {"native_pause","()I",(void*)native_pause },  
    12.     {"native_resume","()I",(void*)native_resume },  
    13.     {"native_get_current_position","()J",(void*)native_get_current_position },  
    14.     {"native_setSpeed","(I)I",(void*)native_setSpeed },  
    15.     {"native_getSynSpeed","()I",(void*)native_getSynSpeed },  
    16.     {"native_finalize","()I",(void*)native_finalize },  
    17.     {"native_delete","()I",(void*)native_delete },  
    18. };  
    19.   
    20. //Class path name for Register   
    21. static const char *classPathName = "android/tts/TTS";  
    22.   
    23. /* 
    24.  * Register several native methods for one class. 
    25.  */  
    26. static int registerNativeMethods(JNIEnv* env, const char* className,  
    27.                                  JNINativeMethod* gMethods, int numMethods)  
    28. /* 
    29.  * Register native methods for all classes we know about. 
    30.  * 
    31.  * returns JNI_TRUE on success. 
    32.  */  
    33. static int registerNatives(JNIEnv* env)  
    34. {  
    35.     if (!registerNativeMethods(env, classPathName,  
    36.                                methods, sizeof(methods) / sizeof(methods[0]))) {  
    37.         return JNI_FALSE;  
    38.     }  
    39.   
    40.   
    41.     return JNI_TRUE;  
    42. }  
    43.   
    44. java文件中  
    45.    
    46.     static native int native_create(int streamType);  
    47.     static native int native_setSpeed(int speed);  
    48.     static native int native_setText(byte str[],long length,int islast);  
    49.     static native int native_clearText(int appID);  
    50.     static native int native_start();  
    51.     static native int native_next();  
    52.     static native int native_flush();  
    53.     static native int native_pause();  
    54.     static native int native_resume();  
    55.     static native int native_stop();   
    56.     static native int native_finalize();  
    57.     static native int native_delete();  
    58.     static native int native_getSynSpeed();  
    59.     static native boolean native_isPlaying();  
    60.     static native long native_get_current_position();  


     

    JNI组件的入口函数——JNI_OnLoad()、JNI_OnUnload()

    JNI组件被成功加载和卸载时,会进行函数回调,当VM执行到System.loadLibrary(xxx)函数时,首先会去执行JNI组件中的JNI_OnLoad()函数,而当VM释放该组件时会呼叫JNI_OnUnload()函数。先看示例代码:


     

    1. typedef union {  
    2.     JNIEnv* env;  
    3.     void* venv;  
    4. } UnionJNIEnvToVoid;  
    5.   
    6. /* This function will be call when the library first be loaded */  
    7. jint JNI_OnLoad(JavaVM* vm, void* reserved)  
    8. {  
    9.     UnionJNIEnvToVoid uenv;  
    10.     JNIEnv* env = NULL;  
    11.     LOGI("JNI_OnLoad!");  
    12.   
    13.     if (vm->GetEnv((void**)&uenv.venv, JNI_VERSION_1_4) != JNI_OK) {  
    14.         LOGE("ERROR: GetEnv failed");  
    15.         return -1;  
    16.     }  
    17.   
    18.     env = uenv.env;;  
    19.   
    20.     if (registerNatives(env) != JNI_TRUE) {  
    21.         LOGE("ERROR: registerNatives failed");  
    22.         return -1;  
    23.     }  
    24.   
    25.      return JNI_VERSION_1_4;  
    26. }  

    JNI_OnLoad()有两个重要的作用:

    • 指定JNI版本:告诉VM该组件使用那一个JNI版本(若未提供JNI_OnLoad()函 数,VM会默认该使用最老的JNI 1.1版),如果要使用新版本的JNI,例如JNI 1.4版,则必须由JNI_OnLoad()函数返回常量JNI_VERSION_1_4(该常量定义在jni.h中) 来告知VM。
    • 初始化设定,当VM执行到System.loadLibrary()函数时,会立即先呼叫JNI_OnLoad()方法,因此在该方法中进行各种资源的初始化操作最为恰当。

    JNI_OnUnload()的作用与JNI_OnLoad()对应,当VM释放JNI组件时会呼叫它,因此在该方法中进行善后清理,资源释放的动作最为合适。


    JNI中的日志输出
    你一定非常熟悉在Java代码中使用Log.x(TAG,“message”)系列方法,在c/c++代码中也一样,不过首先你要include相关头文件。遗憾的是你使用不同的编译环境( 请参考上文中两种编译环境的介绍) ,对应的头文件略有不同。。
    如果是在完整源码编译环境下,只要include <utils/Log.h>头文件,就可以使用对应的LOGI、LOGD等方法了,同时请定义LOG_TAG,LOG_NDEBUG等宏值,示例代码如下:

    1. #define LOG_TAG "HelloJni"  
    2. #define LOG_NDEBUG 0  
    3. #define LOG_NIDEBUG 0  
    4. #define LOG_NDDEBUG 0  
    5.   
    6.   
    7. #include <string.h>  
    8. #include <jni.h>  
    9. #include <utils/Log.h>  
    10. jstring Java_com_inc_android_ime_HelloJni_stringFromJNI(JNIEnv* env,jobject thiz){  
    11.     LOGI("Call stringFromJNI! ");  
    12.     return (*env)->NewStringUTF(env, "Hello from JNI (中文)!");  
    13. }  


    JNI 的对应数据类型针对java和c++

    c/c++方法和Java方法之间映射关系的关键是 JNINativeMethod 结构,该结构定义在jni.h中,具体定义如下:

     

    1. typedef struct {   
    2.   const char* name;//java方法名称   
    3.   const char* signature; //java方法签名  
    4.   void*       fnPtr;//c/c++的函数指针  
    5. } JNINativeMethod;  


    参照上文示例中初始化该结构的代码:

    1. //定义方法隐射关系  
    2. static JNINativeMethod methods[] = {  
    3.   {"sayHello", "(Ljava/lang/String;)Ljava/lang/String;", (void*)sayHello},  
    4. };  

    其中比较难以理解的是第二个参数——signature字段的取值,实际上这些字符与函数的 参数类型/返回类型一一对应,其中"()" 中的字符表示参数,后面的则代表返回值。例如"()V" 就表示void func(),"(II)V" 表示 void func(int, int),具体的每一个字符的对应关系如下:

    字符     Java类型     C/C++类型
    V           void          void
    Z         jboolean      boolean
    I            jint            int
    J           jlong          long
    D         jdouble       double
    F          jfloat          float
    B          jbyte          byte
    C          jchar           char
    S          jshort         short

     

    数组则以"["开始,用两个字符表示:

    字符     java类型          c/c++类型
    [Z     jbooleanArray      boolean[]
    [I        jintArray            int[]
    [F       jfloatArray         float[]
    [B      jbyteArray          byte[]
    [C      jcharArray          char[]
    [S      jshortArray         short[]
    [D     jdoubleArray       double[]
    [J        jlongArray          long[]

     

    上面的都是基本类型,如果参数是Java类,则以"L"开头,以";"结尾,中间是用"/" 隔开包及类名,而其对应的C函数的参数则为jobject,一个例外是String类,它对应C类型jstring,例如:Ljava/lang /String; 、Ljava/net/Socket; 等,如果JAVA函数位于一个嵌入类(也被称为内部类),则用$作为类名间的分隔符,例如:"Landroid/os /FileUtils$FileStatus;"。


    In C, all other JNI reference types are defined to be the same as jobject. For example:

    typedef jobject jclass; 
    

    In C++, JNI introduces a set of dummy classes to enforce the subtyping relationship. For example:

    class _jobject {}; 
    class _jclass : public _jobject {}; 
    ... 
    typedef _jobject *jobject; 
    typedef _jclass *jclass; 
    

    Field and Method IDs

    Method and field IDs are regular C pointer types:

    struct _jfieldID;              /* opaque structure */ 
    typedef struct _jfieldID *jfieldID;   /* field IDs */ 
     
    struct _jmethodID;              /* opaque structure */ 
    typedef struct _jmethodID *jmethodID; /* method IDs */ 
    

    The Value Type

    The jvalue union type is used as the element type in argument arrays. It is declared as follows:

    typedef union jvalue { 
        jboolean z; 
        jbyte    b; 
        jchar    c; 
        jshort   s; 
        jint     i; 
        jlong    j; 
        jfloat   f; 
        jdouble  d; 
        jobject  l; 
    } jvalue; 
    

    Type Signatures

    The JNI uses the Java VM’s representation of type signatures. Table 3-2 shows these type signatures.

     

    Table 3-2 Java VM Type Signatures
    Type Signature
    Java Type
    Z
    boolean
    B
    byte
    C
    char
    S
    short
    I
    int
    J
    long
    F
    float
    D
    double
    L fully-qualified-class ;
    fully-qualified-class
    [ type
    type[]
    ( arg-types ) ret-type
    method type

     

    For example, the Java method:

    long f (int n, String s, int[] arr); 
    

    has the following type signature:

    (ILjava/lang/String;[I)J 



    参考的资料:http://download.oracle.com/javase/1.5.0/docs/guide/jni/spec/types.html#wp568

                        http://www.top-e.org/jiaoshi/html/?168.html

                        http://neillife.blogspot.com/2009/01/how-to-add-new-module-to-android.html

                        http://blog.csdn.net/zhenyongyuan123/article/details/5862054

                              http://download.oracle.com/javase/1.5.0/docs/guide/jni/spec/jniTOC.html

                              http://cnetwei.iteye.com/blog/825306

  • 相关阅读:
    nginx 配置https详细步骤
    Git 上传本地仓库到远程git仓库
    VUE 配置vscode关于vue插件
    ORA-01439:要更改数据类型,则要修改的列必须为空
    Oracle查看主键、删除主键、添加联合主键
    std::stoi, std::stol, std::stoll
    C+++string类如何判断字符串为空
    1day漏洞反推技巧实战(1)
    java反射笔记,自用
    tomcat Valve内存马
  • 原文地址:https://www.cnblogs.com/bluestorm/p/4906908.html
Copyright © 2020-2023  润新知